为了账号安全,请及时绑定邮箱和手机立即绑定

JavaWeb —— 上传文件

标签:
Java

index.jsp 上传文件页
uploaded.jsp 上传页
UploadFileServlet.java uploaded.jsp的Servlet,用于上传文件
1.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Upload your file.</title>
</head>
<body>
<form action="/uploaded.jsp" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit" value="Submit">Submit</button>
    <button type="reset" value="Reset">Reset</button>
</form>
</body>
</html>
  1. uploaded.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Upload!</title>
</head>
<body>

</body>
</html>
  1. UploadFileServlet.java
package lh.upload;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "UploadServlet", urlPatterns = "/uploaded.jsp")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!ServletFileUpload.isMultipartContent(request)) {
            PrintWriter writer = response.getWriter();
            writer.println("Error: enctype=multipart/form-data");
            writer.flush();
            return;
        }

        // 以下6行代码记住就好
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 3); // 30 MB
        diskFileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
        fileUpload.setFileSizeMax(1024 * 1024 * 30);  //文件最大为30MB
        fileUpload.setSizeMax(1024 * 1024 * 50);

        String fileUploadPath = getServletContext().getRealPath("./") + File.separator + "uploads";
        // 文件存放路径
        File uploadFileDir = new File(fileUploadPath);

        // 判断文件夹是否存在
        if (!uploadFileDir.exists()) {
            uploadFileDir.mkdir();
        }

        try {

            @SuppressWarnings("unchecked")
            List<FileItem> fileItemList = fileUpload.parseRequest(new ServletRequestContext(request));

            // 遍历文件列表并上传
            if (fileItemList != null && fileItemList.size() > 0) {
                for (FileItem item : fileItemList) {
                    String fn = new File(item.getName()).getName();
                    String fp = fileUploadPath + File.separator + fn;
                    File storeFile = new File(fp);
                    System.out.println(fp);
                    item.write(storeFile);
                    request.setAttribute("resMsg", "OK");
                }
            }

        } catch (Exception ex) {
            request.setAttribute("exMsg", ex.getMessage());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
点击查看更多内容
7人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消