java文件上传与下载工具类,可实现图片的上传与下载,基于servlet

7 篇文章 0 订阅
本文详细讲解了如何利用ApacheCommonsFileUpload在Java中构建一个支持文件上传和下载的工具类,涉及解析请求、存储文件操作。
摘要由CSDN通过智能技术生成
package com.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


public class FileUtil {
    /**
     * 上传工具类  上传就是对前端获取的请求进行解析,对其中的文件数据进行write操作
     */
    public static Map<String,String> upload(HttpServletRequest req,String path){
        //创建map集合存放信息
        Map<String,String> map=new HashMap<>();
        //设置字符集
        String encode="utf-8";

        DiskFileItemFactory factory=new DiskFileItemFactory();
        FileUpload fileUpload=new FileUpload(factory);

        try {
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()){  //如果是普通表单数据

                    String fieldName = fileItem.getFieldName();
                    String value = fileItem.getString(encode);  //从表单中获取对应的参数值与值
                    //存放信息
                    map.put(fieldName,value);

                }else { //如果是文件

                    String oldName = fileItem.getName();

                    String newName=null; //如果文件为空,将其设置为空

                    if (oldName!=null && (!"".equals(oldName))){
                        //对文件名进行重新赋值
                        UUID uuid=UUID.randomUUID();
                        newName= uuid + oldName.substring(oldName.lastIndexOf("."));

                        //写出文件
                        fileItem.write(new File(path,newName));
                    }

                    //存放信息
                    map.put(fileItem.getFieldName(),newName);
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 下载工具类    下载就是从本地输入数据再响应输出(后期从服务器下载)
     */
    public static void download(String path, HttpServletResponse resp){
        //获取文件名
        String fileName = path.substring(path.lastIndexOf("/")+1);
        //让浏览器进行下载
        resp.setHeader("Content-Disposition","attachment;fileName="+fileName);

        //创建本地输入流与响应输出流
        FileInputStream in= null;
        ServletOutputStream out =null;
        try {

            in = new FileInputStream(path);
            out = resp.getOutputStream();
            //创建字节数组
            byte[] bytes=new byte[1024];
            int length;

            while ((length=in.read(bytes))!=-1){
                out.write(bytes,0,length);
            }

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {

                if (in!=null){
                    in.close();
                }
                if (out!=null){
                    out.close();
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

应用场景:

上传

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("type/html;charset=utf-8");

        //上传到服务器
        String realPath = req.getServletContext().getRealPath("/img");
        //new File(realPath).mkdirs();

        System.out.println(realPath);

       // Map<String, String> upload = FileUtil.upload(req, "d:/log");
        Map<String, String> upload = FileUtil.upload(req, realPath);
        for (String s : upload.keySet()) {
            String value = upload.get(s);
            System.out.println(s+" : "+value);
        }

    }

下载

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //接收前端请求路径
        String path = req.getParameter("path");

        FileUtil.download(path,resp);
      
    }

注意,别忘了导包
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

四夕兴言

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值