文件上传下载的工具类

由于经常用到文件上传下载,每次都需要去网上寻找,所以我自己讲我以前用过的一些方法给结合在一起写成了这个工具类。
工具类有两种方式上传,一种是base64,常用于客户端上传图片;另一种是一文件形式上传,常用于网页端上传文件。

package com.chj.util;

import cn.jpush.api.utils.StringUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author Jun
 * @Date 2018/8/25 8:59
 * @Description 文件上传下载工具类
 */
public class FileOperationUtil {
    //默认文件编码 utf-8
    private static final String ENCODING = "UTF-8";
    //默认文件大小50M
    private static final long DEFAULT_MAX_SIZE = 52428800;


    /**
     * 文件下载
     *
     * @param filePath 文件路径
     * @return
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public static ResponseEntity<byte[]> download(String filePath) throws UnsupportedEncodingException, IOException {
        String fileName = FilenameUtils.getName(filePath);
        return downloadAssist(filePath, fileName);
    }

    /**
     * 文件下载
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     * @return
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public static ResponseEntity<byte[]> download(String filePath, String fileName) throws UnsupportedEncodingException, IOException {
        return downloadAssist(filePath, fileName);
    }

    /**
     * 文件下载辅助
     *
     * @param filePath 文件路径
     * @param fileName 文件名
     * @return
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    private static ResponseEntity<byte[]> downloadAssist(String filePath, String fileName) throws UnsupportedEncodingException, IOException {
        File file = new File(filePath);
        if (!file.isFile() || !file.exists()) {
            throw new IllegalArgumentException("filePath 参数必须是真实存在的文件路径:" + filePath);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, ENCODING));
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /**
     * 多文件上传
     *
     * @param request  当前上传的请求
     * @param basePath 保存文件的路径
     * @return Map<String, String> 返回上传文件的保存路径 以文件名做map的key;文件保存路径作为map的value
     * @throws IOException
     * @throws IllegalStateException
     */
    public static Map<String, String> multiFileUpload(HttpServletRequest request, String basePath) throws IllegalStateException, IOException {
        if (!(new File(basePath).isDirectory())) {
            throw new IllegalArgumentException("basePath 参数必须是文件夹路径");
        }
        return multifileUploadAssist(request, basePath, null);
    }

    /**
     * 多文件上传
     *
     * @param request  当前上传的请求
     * @param basePath 保存文件的路径
     * @param exclude  排除文件名字符串,以逗号分隔的,默认无可传null
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    public static Map<String, String> multiFileUpload(HttpServletRequest request, String basePath, String exclude) throws IllegalStateException, IOException {
        if (!(new File(basePath).isDirectory())) {
            throw new IllegalArgumentException("basePath 参数必须是文件夹路径");
        }
        return multifileUploadAssist(request, basePath, exclude);
    }

    /**
     * 多文件上传辅助
     *
     * @param request  当前上传的请求
     * @param basePath 保存文件的路径
     * @param exclude  排除文件名字符串,以逗号分隔的,默认无可传null
     * @return
     * @throws IOException
     */
    private static Map<String, String> multifileUploadAssist(HttpServletRequest request, String basePath, String exclude) throws IOException {
        exclude = exclude == null ? "" : exclude;

        Map<String, String> filePaths = new HashMap<String, String>();
        File file = null;
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // get the parameter names of the MULTIPART files contained in this request
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 取得上传文件
                List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next());
                for (MultipartFile multipartFile : multipartFiles) {
                    String fileName = multipartFile.getOriginalFilename();
                    if (StringUtils.isNotEmpty(fileName) && (!exclude.contains(fileName))) {
                        file = new File(basePath + changeFilename2UUID(fileName));
                        filePaths.put(fileName, file.getPath());
                        multipartFile.transferTo(file);
                    }
                }
            }
        }
        return filePaths;
    }

    /**
     * 将文件名转变为UUID命名的 ,保留文件后缀
     *
     * @param filename
     * @return
     */
    public static String changeFilename2UUID(String filename) {
        String uuid = UUID.randomUUID().toString();
        return uuid + "." + FilenameUtils.getExtension(filename);
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public static void deleteFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件到根目录
     *
     * @param file
     * @return
     * @throws IOException
     * @throws FileUploadBase.FileSizeLimitExceededException
     */
    public static String uploadFile(MultipartFile file) throws IOException, FileUploadBase.FileSizeLimitExceededException {
        assertAllowed(file);
        String originalFilename = file.getOriginalFilename();
        String fileName = changeFilename2UUID(originalFilename);
        String path = System.getProperty("user.dir");
        path.replace("\\", "/");
        String filePathName = path + fileName;
        if (upload(file, path, filePathName)) {
            return filePathName;
        }
        return "";
    }

    /**
     * 上传文件到指定存储位置
     *
     * @param file
     * @param filePath
     * @return
     * @throws IOException
     * @throws FileUploadBase.FileSizeLimitExceededException
     */
    public static String uploadFile(MultipartFile file, String filePath) throws IOException, FileUploadBase.FileSizeLimitExceededException {
        assertAllowed(file);
        String originalFilename = file.getOriginalFilename();
        String fileName = changeFilename2UUID(originalFilename);
        String filePathName = filePath + fileName;
        if (upload(file, filePath, filePathName)) {
            return filePathName;
        }
        return "";
    }

    /**
     * 多文件上传到指定位置
     *
     * @param files
     * @param filePath
     * @return
     * @throws IOException
     * @throws FileUploadBase.FileSizeLimitExceededException
     */
    public static String uploadFile(MultipartFile[] files, String filePath) throws IOException, FileUploadBase.FileSizeLimitExceededException {
        StringBuilder stringBuilder = new StringBuilder();
        for (MultipartFile file : files) {
            assertAllowed(file);
            String originalFilename = file.getOriginalFilename();
            String fileName = changeFilename2UUID(originalFilename);
            String filePathName = filePath + fileName;
            if (upload(file, filePath, filePathName)) {
                stringBuilder.append(filePathName).append(";");
            }
        }
        String str = stringBuilder.toString();
        str.substring(0, str.length() - 1);
        return str;
    }

    /**
     * 多文件上传到根目录
     *
     * @param files
     * @return
     * @throws IOException
     * @throws FileUploadBase.FileSizeLimitExceededException
     */
    public static String uploadFile(MultipartFile[] files) throws IOException, FileUploadBase.FileSizeLimitExceededException {
        StringBuilder stringBuilder = new StringBuilder();
        String path = System.getProperty("user.dir");
        path.replace("\\", "/");
        for (MultipartFile file : files) {
            assertAllowed(file);
            String originalFilename = file.getOriginalFilename();
            String fileName = changeFilename2UUID(originalFilename);
            String filePathName = path + fileName;
            if (upload(file, path, filePathName)) {
                stringBuilder.append(filePathName).append(";");
            }
        }
        String str = stringBuilder.toString();
        str.substring(0, str.length() - 1);
        return str;
    }

    /**
     * 校验上传文件的大小
     *
     * @param file
     * @throws FileUploadBase.FileSizeLimitExceededException
     */
    public static final void assertAllowed(MultipartFile file) throws FileUploadBase.FileSizeLimitExceededException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileUploadBase.FileSizeLimitExceededException("not allowed upload upload", size, DEFAULT_MAX_SIZE);
        }
    }

    /**
     * base64上传图片到根目录
     *
     * @param base64Str
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String base64StrUpload(String base64Str, String name) throws FileNotFoundException, IOException {
        String filePathName = System.getProperty("user.dir") + "/" + name;
        if (base64Upload(base64Str, filePathName)) {
            return filePathName;
        }
        return "";

    }

    /**
     * base64上传图片到指定文件夹
     *
     * @param base64Str
     * @param filePath
     * @param name
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String base64StrUpload(String base64Str, String filePath, String name) throws FileNotFoundException, IOException {
        String filePathName = filePath + name;

        if (base64Upload(base64Str, filePathName)) {
            return filePathName;
        }
        return "";
    }

    private static boolean base64Upload(String base64Str, String filePathName)
            throws IOException {
        if (base64Str == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        //Base64解码
        byte[] b = decoder.decodeBuffer(base64Str);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {//调整异常数据
                b[i] += 256;
            }
        }
        //生成jpeg图片
        OutputStream out = new FileOutputStream(filePathName);
        out.write(b);
        out.flush();
        out.close();
        return true;
    }

    private static boolean upload(MultipartFile file, String filePathName, String filePath) {
        try {
            byte[] bytes = file.getBytes();
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            FileOutputStream out = new FileOutputStream(filePathName);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

有问题请联系我,谢谢大家指点!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值