java文件上传下载工具类FileUtils

上传:

package com.yonyougov.dmp.amserver.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;


/**
 * @Description TODO  文件上传工具类
 * @Author yitianRen
 * @Date 2019/10/10 10:51
 * @Version 1.0
 **/
public class FileUploadUtils {

    private static Logger logger = LoggerFactory.getLogger(FileDownloadUtils.class);
    /**
     * @Author: yitianRen
     * @Description:
     * @Date: 16:00 2019/10/10
     * @Param: file:文件 rootDir:上传跟路径
     * @Return:
    */
    public static String upLoadFile(MultipartFile file, String rootDir) {
        logger.info("传入的文件参数:{}", JSON.toJSONString(file, true));
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.info("文件为空");
            return "文件为空,请重新上传";
        }
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(rootDir + file.getOriginalFilename());
            //如果没有files文件夹,则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(rootDir));
            }
            //文件写入指定路径
            Files.write(path, bytes);
            logger.debug("文件写入成功...");
            return "文件上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "后端异常...";
        }
    }


}

下载:

package com.yonyougov.dmp.amserver.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Description TODO 下载文件工具类
 * @Author yitianRen
 * @Date 2019/10/9 10:03
 * @Version 1.0
 **/
public class FileDownloadUtils {

    /**
     * @Author: yitianRen
     * @Description: 文件下载,输入文件名和文件路径
     * @Date: 14:03 2019/10/9
     * @Param:
     * @Return:
    */
    public static void downloadFile(HttpServletResponse response, String fileName, String path){
        fileName="测试.txt";
        path="D:\\测试.txt";
        if (fileName != null) {
            //设置文件路径
            File file = new File(path);
            if (file.exists()) {
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                try {
                    response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"ISO-8859-1"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

}

 

备注:springboot上传文件出现异常问题java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?  查询得知是配置文件问题,我在***Controller层加入一下代码解决:

@Bean
	public CommonsMultipartResolver multipartResolver() {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
		multipartResolver.setDefaultEncoding("UTF-8");
		multipartResolver.setMaxUploadSize(104857600);
		return multipartResolver;
	}

java文件上传下载工具类FileUtils_第1张图片

你可能感兴趣的:(Utils)