springboot 实现文件上传,下载 所有类型文件,前端使用vue+element,代码在另外一篇博客。

UploadUtils类

package com.qiyuan.qyframe.base.util;

import com.qiyuan.qyframe.base.bo.ResponseData;
import com.qiyuan.qyframe.base.exception.BusiException;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.security.authentication.LockedException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.apache.commons.codec.binary.Base64;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Created Lv hs
 * @Date 18-4-4 下午5:20
 * @Description: 图片上传工具类
 */
public class UploadUtils {

    public static final String UPLOAD_FILE_PATH = "F:\\tupianshangchuan";

    /**
     * 多图上传 返回Json格式
     * @param request
     * @param targetDir 文件上传目标路径
     * @param imgDir 图片上传路径
     * @param param 需要获取的前台传来的参数
     * @return
     */
    public static ResponseData uploadImages(HttpServletRequest request, String targetDir, String imgDir, String param) {
        try {
            if(targetDir==null||targetDir.equals("")){
                targetDir=UPLOAD_FILE_PATH;
            }
            Map<String,Object> maps= new HashMap<>();
            String imageUrl = "";
            if (ServletFileUpload.isMultipartContent(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                Map abc=multipartRequest.getParameterMap();
                if(param!=null&&!param.equals("")){
                    String[] params = multipartRequest.getParameterMap().get(param);
                    if (params != null && params.length > 0) {
                        param = params[0];
                    }
                    maps.put("param",param);
                }
                // 得到上传的图片数据
                List<MultipartFile> portrait = multipartRequest.getFiles("file");
                if (portrait.size() > 0) {
                    List<String> imgs=new ArrayList<String>();
                    MultipartFile[] list = portrait.toArray(new MultipartFile[portrait.size()]);
                    //文件上传目标路径
                    Map<String, Object> map = FileUtils.uploadFiles(list, targetDir,
                            imgDir, request, "images", 1);
                    if ((boolean)map.get("success")) {
                        List<Map> files=(List<Map>)map.get("files");
                        for(Map m:files){
                            System.out.println("----图片路径----"+m.toString());
                        }
                        maps.put("files",files);
                        //多图片的情况,有可能存在有图片上传成功,有图片上传失败情况,需要前端再次去判断

                    return ResponseDataUtil.buildSuccess(maps);
                }else{
                    return ResponseDataUtil.buildError(map.get("msg").toString());
                }
                }
            }
            return ResponseDataUtil.buildError("没有图片数据");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDataUtil.buildError(e.getMessage());
        }
    }

    /**
     * 单图上传 返回Json格式
     * @param request
     * @param targetDir 文件上传目标路径
     * @param imgDir 图片上传路径
     * @param param 需要获取的前台传来的参数
     * @return
     */
    public static ResponseData uploadImage(HttpServletRequest request, String targetDir, String imgDir, String param) {
        try {
            if(targetDir==null||targetDir.equals("")){
                targetDir=UPLOAD_FILE_PATH;
            }
            Map<String,Object> maps= new HashMap<>();
            if (ServletFileUpload.isMultipartContent(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                if(param!=null&&!param.equals("")){
                    String[] params = multipartRequest.getParameterMap().get(param);
                    if (params != null && params.length > 0) {
                        param = params[0];
                    }
                    maps.put("param",param);
                }
                // 得到上传的图片数据
                MultipartFile portrait = multipartRequest.getFile("file");
                //文件上传目标路径
                Map<String, Object> map = FileUtils.fileUpload(portrait, targetDir,
                        imgDir, request, "images", 1);
                if ((boolean)map.get("success")) {
                    maps.put("file",map);
                    //多图片的情况,有可能存在有图片上传成功,有图片上传失败情况,需要前端再次去判断
                    return ResponseDataUtil.buildSuccess(maps);
                }else{
                    return ResponseDataUtil.buildError(map.get("result").toString());
                }
            }
            return ResponseDataUtil.buildError("没有图片数据");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDataUtil.buildError(e.getMessage());
        }
    }

    /**
     * 文档上传 返回Json格式
     * @param request
     * @param targetDir 文件上传目标路径
     * @param imgDir 文档上传路径
     * @param param 需要获取的前台传来的参数
     * @return
     */
    public static ResponseData uploadFile(HttpServletRequest request, String targetDir, String imgDir,String type, String param) {
        try {
            if(targetDir==null||targetDir.equals("")){
                targetDir=UPLOAD_FILE_PATH;
            }
            Map<String,Object> maps= new HashMap<>();
            if (ServletFileUpload.isMultipartContent(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                if(param!=null&&!param.equals("")){
                    String[] params = multipartRequest.getParameterMap().get(param);
                    if (params != null && params.length > 0) {
                        param = params[0];
                    }
                    maps.put("param",param);
                }
                // 得到上传的图片数据
                MultipartFile portrait = multipartRequest.getFile("file");
                //文件上传目标路径
                Map<String, Object> map = FileUtils.fileUpload(portrait, targetDir,
                        imgDir, request, type, 1);
                if ((boolean)map.get("success")) {
                    maps.put("file",map);
                    //多图片的情况,有可能存在有图片上传成功,有图片上传失败情况,需要前端再次去判断
                    return ResponseDataUtil.buildSuccess(maps);
                }else{
                    return ResponseDataUtil.buildError(map.get("result").toString());
                }
            }
            return ResponseDataUtil.buildError("没有文档数据!");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDataUtil.buildError(e.getMessage());
        }
    }

    /**
     * 多文档上传 返回Json格式
     * @param request
     * @param targetDir 文件上传目标路径
     * @param imgDir 文档上传路径
     * @param param 需要获取的前台传来的参数
     * @return
     */
    public static ResponseData uploadFiles(HttpServletRequest request, String targetDir, String imgDir, String param) {
        try {
            if(targetDir==null||targetDir.equals("")){
                targetDir=UPLOAD_FILE_PATH;
            }
            Map<String,Object> maps= new HashMap<>();
            String imageUrl = "";
            if (ServletFileUpload.isMultipartContent(request)) {
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                Map abc=multipartRequest.getParameterMap();
                if(param!=null&&!param.equals("")){
                    String[] params = multipartRequest.getParameterMap().get(param);
                    if (params != null && params.length > 0) {
                        param = params[0];
                    }
                    maps.put("param",param);
                }
                // 得到上传的图片数据
                List<MultipartFile> portrait = multipartRequest.getFiles("file");
                if (portrait.size() > 0) {
                    List<String> imgs=new ArrayList<String>();
                    MultipartFile[] list = portrait.toArray(new MultipartFile[portrait.size()]);
                    //文件上传目标路径
                    Map<String, Object> map = FileUtils.uploadFiles(list, targetDir,
                            imgDir, request, "files", 1);
                    if ((boolean)map.get("success")) {
                        List<Map> files=(List<Map>)map.get("files");
                        for(Map m:files){
                            System.out.println("----文档路径----"+m.toString());
                        }
                        maps.put("files",files);
                        //多图片的情况,有可能存在有图片上传成功,有图片上传失败情况,需要前端再次去判断
                    return ResponseDataUtil.buildSuccess(maps);
                }else{
                    return ResponseDataUtil.buildError(map.get("msg").toString());
                }
                }
            }
            return ResponseDataUtil.buildError("没有文档数据!");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDataUtil.buildError(e.getMessage());
        }
    }

    /**
     *  删除单个文件,删除项目路径下文件
     * @param deleteFilePath 要删除的文件路径
     * @return
     */
    public static ResponseData deleteFile(String deleteFilePath) {
        String path = deleteFilePath.replaceAll("\"", "");
        System.out.println("path---" + path);
        File file = new File(UPLOAD_FILE_PATH + path);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return ResponseDataUtil.buildSuccess();
            } else {
                return ResponseDataUtil.buildError("删除失败");
            }
        } else {
            return ResponseDataUtil.buildError("文件未上传至服务器");
        }
    }

    public static void responseTo(File file, HttpServletResponse res, HttpServletRequest request) {  //将文件发送到前端
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        // 获得请求头中的user-agent
        String agent = request.getHeader("User-Agent");
        String fileName = file.getName();
        try {
            if (agent.contains("MSIE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
            } else if (agent.contains("Firefox")) {
                Base64 base64Encoder = new Base64();
                fileName = "=?utf-8?B?" + base64Encoder.encode(fileName.getBytes("utf-8"));
            } else {
                fileName = URLEncoder.encode(fileName, "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            throw BusiException.le("文件下载错误");
        }
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

FileUtils类

package com.qiyuan.qyframe.base.util;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Created Lv hs
 * @Date 18-4-4 下午2:12
 * @Description: TODO()
 */
public class FileUtils {

    static final String success = "success";
    static final String result = "result";
    static final String fileName = "filename";
    static final String originalfilename = "originalfilename";//图片员名称
    static final String ret = "ret";
    static final String data = "data";
    // 最大文件大小
    private static long maxSize = 500000000;

    // 定义允许上传的文件扩展名
    private static final Map<String, String> extMap = new HashMap<String, String>();

    static {
        // 其中images,flashs,medias,files,对应文件夹名称,对应dirName
        // key文件夹名称
        // value该文件夹内可以上传文件的后缀名
        extMap.put("images", "gif,GIF,jpg,JPG,jpeg,JPEG,png,PNG,bmp,BMP");
        extMap.put("flashs", "swf,SWF,flv,FLV");
        extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB");
        extMap.put("files", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,DOC,DOCX,XLS,XLSX,PPT,HTM,HTML,TXT,ZIP,RAR,GZ,BZ2,pdf");
        extMap.put("sensitive", "txt,TXT");
    }

    /**
     * 上传文件-多文件上传
     * @param myFiles
     * @param targetDir
     * @param imgDir
     * @param type  文件格式类型
     * @param rename  是否重命名 0:原文件名 1:文件重命名
     * @return
     */
    public static Map<String,Object> uploadFiles(MultipartFile[] myFiles,
                                                 String targetDir, String imgDir, HttpServletRequest request, String type, int rename) throws IOException {
        Map<String,Object> map = new HashMap<>();
        List<Map> files=new ArrayList<>();
        try {
            for(MultipartFile myFile : myFiles){
                Map<String,Object> map1 = fileUpload(myFile, targetDir, imgDir,request,type,rename);
                if((boolean)map1.get(success)){
                    Map<String,Object> f=new HashMap<>();
                    f.put("relativePath",map1.get(result).toString());
                    f.put("filename",map1.get(fileName).toString());
                    f.put("originFilename",map1.get("originalfilename").toString());
                    f.put(success,true);
                    files.add(f);
                }else{
                    Map<String,Object> f=new HashMap<>();
                    f.put(success, false);
                    f.put("filename",map1.get(fileName).toString());
                    f.put("originFilename",map1.get("originalfilename").toString());
                    files.add(f);
                }
            }
            map.put(success, true); // 没有异常出现的情况下,默认都是处理成功
            map.put("files",files);
            return map;
        } catch (NullPointerException e) {
            map.put(success,false);
            map.put("msg",e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            map.put(success,false);
            map.put("msg",e.getMessage());
            e.printStackTrace();
        }

        return map;
    }

    /**
     * 上传文件-单文件上传
     * @param myFile
     * @param targetDir
     * @param imgDir
     * @param type  文件格式类型
     * @param rename  是否重命名 0:原文件名 1:文件重命名
     * @return
     * @throws IOException
     * @throws NullPointerException
     */
    public static Map<String,Object> fileUpload(MultipartFile myFile,
                                                String targetDir, String imgDir, HttpServletRequest request, String type, int rename) throws IOException,NullPointerException {

        Map<String,Object> map =new HashMap<>();
        String originalFilename ;
        map.put(success,false);
        // boolean errorFlag = true;
        // 获取内容类型
        String contentType = request.getContentType();
        int contentLength = request.getContentLength();
        // 文件保存目录路径
        String savePath = targetDir;
        // 文件保存目录URL
        File uploadDir = new File(savePath);
        String fileExt = myFile.getOriginalFilename().substring(myFile.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();

        if(myFile.isEmpty()){
            //上传图片为空
            map.put(result, "请选择文件后上传");
        }else if (!Arrays.asList(extMap.get(type).split(",")).contains(fileExt)) {// 检查扩展名
            map.put(result, "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(type) + "格式。");
        } else if (contentType == null || !contentType.startsWith("multipart")) {
            System.out.println("请求不包含multipart/form-data流");
            map.put(result, "请求不包含multipart/form-data流");
        } else if (maxSize < contentLength) {
            System.out.println("上传文件大小超出文件最大大小");
            map.put(result, "上传文件大小超出文件最大大小[" + convertFileSize(maxSize) + "]");
        } else if (!ServletFileUpload.isMultipartContent(request)) {
            map.put(result, "请选择文件");
        } else if (!uploadDir.isDirectory()) {// 检查目录
            map.put(result, "上传目录[" + savePath + "]不存在");
        } else if (!uploadDir.canWrite()) {
            map.put(result, "上传目录[" + savePath + "]没有写权限");
        } else{
            mkdir(targetDir + imgDir);
            if(rename==0){
                originalFilename = myFile.getOriginalFilename();
                org.apache.commons.io.FileUtils.copyInputStreamToFile(myFile.getInputStream(),
                        new File(targetDir + imgDir, originalFilename));
                map.put("totalSize", getSize((double) myFile.getInputStream().available()));
                map.put(result, imgDir + "/" + originalFilename);
                map.put(fileName , originalFilename);
                map.put("originalfilename", myFile.getOriginalFilename());
                map.put(success, true);
            }else{
                originalFilename = String.valueOf(new IdGen().getNextId())+
                        myFile.getOriginalFilename().substring( myFile.getOriginalFilename().lastIndexOf("."));
                org.apache.commons.io.FileUtils.copyInputStreamToFile(myFile.getInputStream(),
                        new File(targetDir + imgDir, originalFilename));
                map.put("totalSize", getSize((double) myFile.getInputStream().available()));
                map.put(result, imgDir + "/" + originalFilename);
                map.put(fileName , originalFilename);
                map.put("originalfilename", myFile.getOriginalFilename());
                map.put(success, true);
            }


        }
        return map;
    }

    /**
     * 创建文件夹
     */
    public static boolean mkdir(String path) {
        path = normalizePath(path);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return true;
    }
    /**
     * 将一个字符串中的指定片段全部替换,替换过程中不进行正则处理。<br>
     * 使用String类的replaceAll时要求片段以正则表达式形式给出,有时较为不便,可以转为采用本方法。
     */
    public static String replaceEx(String str, String subStr, String reStr) {
        if (str == null) {
            return null;
        }
        if (subStr == null || subStr.equals("") || subStr.length() > str.length() || reStr == null) {
            return str;
        }
        StringBuffer sb = new StringBuffer();
        int lastIndex = 0;
        while (true) {
            int index = str.indexOf(subStr, lastIndex);
            if (index < 0) {
                break;
            } else {
                sb.append(str.substring(lastIndex, index));
                sb.append(reStr);
            }
            lastIndex = index + subStr.length();
        }
        sb.append(str.substring(lastIndex));
        return sb.toString();
    }
    /**
     * 将文件路径规则化,去掉其中多余的/和\,去掉可能造成文件信息泄漏的../
     */
    public static String normalizePath(String path) {
        path = path.replace('\\', '/');
        path = FileUtils.replaceEx(path, "../", "/");
        path = FileUtils.replaceEx(path, "./", "/");
        if (path.endsWith("..")) {
            path = path.substring(0, path.length() - 2);
        }
        path = path.replaceAll("/+", "/");
        return path;
    }

    public static File normalizeFile(File f) {
        String path = f.getAbsolutePath();
        path = normalizePath(path);
        return new File(path);
    }
    /**
     * 根据字节大小获取带单位的大小。
     * @param size
     * @return
     */
    public static String getSize(double size) {
        DecimalFormat df = new DecimalFormat("0.00");
        if (size > 1024 * 1024) {
            double ss = size / (1024 * 1024);
            return df.format(ss) + " M";
        } else if (size > 1024) {
            double ss = size / 1024;
            return df.format(ss) + " KB";
        } else {
            return size + " bytes";
        }
    }
    /**
     * 文件大小转换为字符串格式
     * @param size 文件大小(单位B)
     * @return
     */
    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }
}

调用:

 /**
     * 附件上传
     * @param request
     * @return
     */
    @RequestMapping("/uploadFile")
    public ResponseData uploadFile(HttpServletRequest request){
        ResponseData responseData = UploadUtils.uploadFile(request, null, "/files/process/qyFrameFile", "files",null);
        if(responseData.getCode().equals("0000")){
            return ResponseDataUtil.buildSuccess(responseData.getData());
        }else {
            return ResponseDataUtil.buildError(responseData.getMsg());
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_41992943/article/details/104651102