【狂神说】文件上传实现

文件上传

        1.导包

                

 

         2.代码实现

                  (1)jsp

                                index.jap

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
<%--
  get 有限制
  post 无限制
--%>
  <body>
  <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
    上传用户:<input type="text" name="username"><br/>
    <p><input type="file" name="file1"></p>
    <p><input type="file" name="file2"></p>
    <br/>
    <hr/>
    <p><input type="submit" value="提交"></p>
  </form>
  </body>
</html>

                                 info.jsp

<%--
  Created by IntelliJ IDEA.
  User: 李亚鑫
  Date: 2022/9/1
  Time: 15:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

                  (2)servlet

package com.liarzn.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@SuppressWarnings("ALL")
public class FileServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断上传网单使普通表单还是文件上传表单
        if (!ServletFileUpload.isMultipartContent(req)) {
            return;//中止方法运行
        }
        //创建上传文件的路径,建议在WEB-INF下,安全,用户无法直接访问上传的文件
        String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdir();//创建目录
        }
        //缓存临时文件
        //临时路径,假如文件超过预期的大小,就把它放到临时文件中,过几天自动删除,或提醒用户转存为永久
        String tmpPath = this.getServletContext().getRealPath("/WEB-INF/upload");
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdir();//创建临时目录
        }
        //处理上传文件,一般都要通过流来获取。使用Apache文件上传组件来实现。
        //common-fileupload 依赖于 common-io 组件

        //1.创建DiskFileItemFactory对象,处理文件上传路径或者限制大小
        DiskFileItemFactory factory = getDiskFileItemFactory(file);

        //2.获取ServletFileUpload
        ServletFileUpload upload = getServletFileUpload(factory);

        //3.处理上传文件
        String msg = null;
        try {
            msg = uploadParseRequest(upload, req, uploadPath);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        req.setAttribute("msg", msg);
        req.getRequestDispatcher("info.jsp").forward(req,resp);
    }

    public static DiskFileItemFactory getDiskFileItemFactory(File file){
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //通过工厂限制缓冲区
        factory.setSizeThreshold(1024*1024);
        factory.setRepository(file);//临时文件的保存目录
        return factory;
    }
    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){
        ServletFileUpload upload = new ServletFileUpload(factory);
        //处理乱码问题
        upload.setHeaderEncoding("utf-8");
        //设置单个文件的上传最大值
        upload.setFileSizeMax(1024*1024*10);
        return upload;
    }

    public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest req, String uploadPath) throws FileUploadException, IOException {
        String msg = "";
        //把前端请求解析封装成一个FileItem对象,需要从ServletFileUpload对象中获取
        List<FileItem> fileItems = upload.parseRequest(req);
        //fileItem为每个表单对象
        for (FileItem fileItem : fileItems) {
            //判断是普通表单还是带文件的表单
            if (fileItem.isFormField()){
                //getFieldName指前端表单控件的name
                String name = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                System.out.println(name+":"+value);
            }else//noinspection LanguageDetectionInspection
            {//文件
                //-------------------------------处理文件-----------------------------------//

                //拿到文件名字
                String uploadFileName = fileItem.getName();
                if (uploadFileName.trim().equals("") || uploadFileName == null){
                    continue;
                }
                //获得上传的文件名
                String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
                //获得上传的文件后缀
                String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

                //使用UUID,保证文件唯一
                String uuidPath = UUID.randomUUID().toString();

                //-------------------------------存放地址-----------------------------------//

                //文件真实存在的路径
                String relPath = uploadPath+"/"+uuidPath;
                //给每个文件创建一个文件夹
                File relPathFile = new File(relPath);
                if (!relPathFile.exists()){
                    relPathFile.mkdir();
                }

                //-----------------------------文件传输完毕----------------------------------//

                //获得文件上传的流
                InputStream inputStream = fileItem.getInputStream();
                //创建一个输出流
                FileOutputStream fos = new FileOutputStream(relPath+"/"+fileName);
                //创建一个缓冲区
                byte[] buffer = new byte[1024*1024];
                //判断是否读取完毕
                int len = 0;
                //如果大于0说明还存在数据
                while ((len = inputStream.read(buffer))>0){
                    fos.write(buffer,0,len);
                }
                //关闭流
                fos.close();
                inputStream.close();

                msg = "文件上传成功!";
                fileItem.delete();//上传成功,清除临时文件
            }
        }
        return msg;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值