文件的上传与下载及解决文件重名问题

Upload

文件上传

文件上传首先在前端页面form表单中需要添加属性enctype=“multipart/form-data” 代表用于发送二进制的文件

获取磁盘工厂对象DiskFileItemFactory

//1.创建磁盘工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();

通过工厂对象获得上传对象ServletFileUpload

//2.通过工厂对象创建上传对象
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

通过上传对象解析请求返回list集合

//3.通过上传对象解析前端发送的复合型表单数据
    List<FileItem> list=null;
    try {
        list = servletFileUpload.parseRequest(request);

遍历list集合

for(FileItem fileItem :list){}

根据是否为文本信息进行处理

if(!fileItem.isFormField()){

获得绝对路径:getServletContext().getRealPath()

上传文件保存到磁盘中

private void upload1(HttpServletRequest request, HttpServletResponse response) {
    //1.创建磁盘工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //2.通过工厂对象创建上传对象
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    //3.通过上传对象解析前端发送的复合型表单数据
    List<FileItem> list=null;
    try {
        list = servletFileUpload.parseRequest(request);
        for(FileItem fileItem :list){
            if(!fileItem.isFormField()){
                //4.获取输入流
                InputStream is = fileItem.getInputStream();
                //5.获取输出流
                FileOutputStream fos = new FileOutputStream("G:/file/" + fileItem.getName());
                byte[] bytes = new byte[1024];
                int len;
                while ((len=is.read(bytes))!=-1){
                    fos.write(bytes,0,len);
                }
                fos.close();
                is.close();
            }
        }
    } catch (FileUploadException | IOException e) {
        e.printStackTrace();
    }
}

上传文件保存到服务器中

//上传文件保存到服务器中
private void upload2(HttpServletRequest request, HttpServletResponse response) {
    //1.创建磁盘工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //2.通过工厂对象创建上传对象
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    //3.通过上传对象解析前端发送的复合型表单数据
    List<FileItem> list=null;
    try {
        list = servletFileUpload.parseRequest(request);
        for(FileItem fileItem:list){
            //判断是否为非文本信息
            if(!fileItem.isFormField()){
                //通过全局对象获取绝对路径
                String path=getServletContext().getRealPath("Upload");
                File file = new File(path);
                //判断路径是否存在,不存在则新建
                if(!file.exists()){
                    file.mkdirs();
                }
                //输出路径,拼接文件名
                File newFile = new File(file, fileItem.getName());
                IOUtils.copy(fileItem.getInputStream(),new FileOutputStream(newFile));
            }
        }
    } catch (FileUploadException | IOException e) {
        e.printStackTrace();
    }
}

解决文件重名问题

方式一:修改图片的名字使用UUID–生成唯一的ID值

private void upload3(HttpServletRequest request, HttpServletResponse response) {
    //获取工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //通过工厂对象获取上传对象
    ServletFileUpload sfu = new ServletFileUpload(factory);
    //通过上传对象解析前端请求
    List<FileItem> list=null;
    try {
        list = sfu.parseRequest(request);
        //判断是否为非文本信息
        for(FileItem fItem:list)
            if (!fItem.isFormField()) {
                //方法一:修改图片的名字
                //使用UUID--生成唯一的ID值
                UUID uuid = UUID.randomUUID();
                //获取绝对路径
                String path = getServletContext().getRealPath("Upload");
                File file = new File(path);
                if(file.exists()){
                    file.mkdirs();
                }
                //file:此处file为路径  后面的为随机uuid值+文件名
                File file1 = new File(file, uuid.toString() + "-" + fItem.getName());
                IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));
    } catch (FileUploadException | IOException e) {
        e.printStackTrace();
    }
}

方式二:通过时间来当做目录

private void upload3(HttpServletRequest request, HttpServletResponse response) {
    //获取工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //通过工厂对象获取上传对象
    ServletFileUpload sfu = new ServletFileUpload(factory);
    //通过上传对象解析前端请求
    List<FileItem> list=null;
    try {
        list = sfu.parseRequest(request);
        //判断是否为非文本信息
        for(FileItem fItem:list)
            if (!fItem.isFormField()) {
        //方法二:通过时间来当做目录
                //获取时间对象
                Date date = new Date();
                //获取时间格式对象
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/HH/mm/ss");
                String format = sdf.format(date);
                //获取绝对路径
                String upload = getServletContext().getRealPath("Upload");
                File file = new File(upload);
                if(!file.exists()){
                    file.mkdirs();
                }
                File file1 = new File(file, fItem.getName());
                IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));

            }
    } catch (FileUploadException | IOException e) {
        e.printStackTrace();
    }
}

方法三,提示重名

//方法三:提示用户重名,需重新命名
                //判断文件是否上传
                if("".equals(fItem.getName())||fItem.getName()==null){
                    //未上传则提示选择图片上传
                    request.setAttribute("msg","请选择图片上传");
                    request.getRequestDispatcher("register.jsp").forward(request,response);
                    return;
                }else {
                    //获取已上传的文件绝对路径
                    String upload = getServletContext().getRealPath("Upload");
                    //路径和文件名拼接
                    File file = new File(upload, fItem.getName());
                    //判断文件是否存在
                    if(file.exists()){
                        request.setAttribute("msg","文件已存在,请重新命名");
                        request.getRequestDispatcher("register.jsp");
                        return;
                    }else {
                        new File(upload).mkdirs();
                        IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file));
                    }
                }

存储完整的表单信息并展示图片

后台servlet代码

private void upload4(HttpServletRequest request, HttpServletResponse response) {
    //获取工厂对象
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //通过工厂对象获取上传对象
    ServletFileUpload sfu = new ServletFileUpload(factory);
    //通过上传对象解析前端请求
    List<FileItem> list=null;
    //创建一个集合用于存放表单信息和图片
    HashMap<String,String> map = new HashMap<>();
    //获取学生对象
    Student student = new Student();
    try {
        list = sfu.parseRequest(request);
        //判断是否为非文本信息
        for(FileItem fItem:list)
            if (!fItem.isFormField()) {
                //方法一:修改图片的名字
                //使用UUID--生成唯一的ID值
                UUID uuid = UUID.randomUUID();
                //获取绝对路径
                String path = getServletContext().getRealPath("Upload");
                File file = new File(path);
                if(file.exists()){
                    file.mkdirs();
                }
                //file:此处file为路径  后面的为随机uuid值+文件名
                File file1 = new File(file, uuid.toString() + "-" + fItem.getName());
                IOUtils.copy(fItem.getInputStream(),new FileOutputStream(file1));
                //存储路径不能为绝对路径
                student.setImgurl("Upload/"+uuid.toString()+"-"+fItem.getName());
            }else {
                //通过key(getFieldNmae--表单的name属性值)获取value(getString--表单的value值)
                String s = map.get(fItem.getFieldName());
                if(s==null){//一次储存
                    map.put(fItem.getFieldName(),fItem.getString());
                }else {//多次储存(复选框)
                    map.put(fItem.getFieldName(),s+","+fItem.getString());
                }
            }
            //把map集合对象数据存放到student对象中
        BeanUtils.populate(student,map);
            request.setAttribute("student",student);
            request.getRequestDispatcher("show.jsp").forward(request,response);
    } catch (FileUploadException | IOException | IllegalAccessException | InvocationTargetException | ServletException e) {
        e.printStackTrace();
    }
}

前端代码

<body>
用户名:${student.username};<br/>
爱好:${student.hobby};<br/>
图片:<img src="${student.imgurl}">
</body>

Download

文件下载

前端提交图片的相对路径

<a href="DownloadServlet?path=Upload/2.jpg">下载</a>

获取图片名字拼接找到绝对路径

//获取文件路径
    String path = request.getParameter("path");
    //获取文件名
    String fileName = path.substring(path.lastIndexOf("/") + 1);
    //转码
    fileName = URLEncoder.encode(fileName, "utf-8");
    
//获取下载图片的绝对路径
    String realPath = getServletContext().getRealPath(path);

设置下载响应头

response.setHeader("Content-disposition","attachment;fileName="+fileName);

通过IO流进行图片拷贝

//获取输入流
    FileInputStream fileInputStream = new FileInputStream(realPath);
    //响应获取输出流
    ServletOutputStream outputStream = response.getOutputStream();
    IOUtils.copy(fileInputStream,outputStream);
    fileInputStream.close();
    outputStream.close();
    原文作者:TiAmo丶Li
    原文地址: https://blog.csdn.net/qq_42891915/article/details/89321160
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞