java上传下载通用方法总结之FileUtils.copyInputStreamToFile

转自:https://blog.csdn.net/m0_37635053/article/details/107029920
java上传下载通用方法总结之FileUtils.copyInputStreamToFile

依赖
<dependency>
    <groupId>commons-io</groupId>
     <artifactId>commons-io</artifactId>
     <version>2.7</version>
 </dependency>

文件上传:

/**
 * 文件上传工具类
 */
public class FileUpload {
    /**
     * @param file     多媒体文件
     * @param filePath 文件上传到的目的路径
     * @param fileName 文件名称(不包括扩展名,即后缀)
     * @return
     */
    public static String fileUpload(MultipartFile file, String filePath, String fileName) throws IOException {
        //扩展名
        String exeName = "";

            if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
                exeName = file.getOriginalFilename().
                        substring(file.getOriginalFilename().lastIndexOf("."));
            }
            copyFile(file.getInputStream(), filePath, fileName + exeName);


        return fileName + exeName;
    }

    /**
     * @param inputStream 文件流
     * @param dir         目的文件夹
     * @param realName    文件全名
     * @return
     * @throws IOException
     */
    private static File copyFile(InputStream inputStream, String dir, String realName) throws IOException {

        File destFile = new File(dir, realName);
        return copyFile(inputStream, destFile);
    }

    private static File copyFile(InputStream inputStream, File destFile) throws IOException {
        if (null == inputStream) {
            return null;
        }
        if (!destFile.exists()) {
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdir();
            }
            destFile.createNewFile();
        }
        FileUtils.copyInputStreamToFile(inputStream, destFile);
        return destFile;
    }
 }

  @PostMapping("/upload")
    public R upload(@RequestBody MultipartFile file){

        String filePath="E:\\2020-in-beijing\\uploadanddownload";
        String fileName = "我的上传文件";
        String s = null;
        try {
            s = FileUpload.fileUpload(file, filePath, fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败!");
        }
        return R.ok("上传成功!").put("data",s);
    }

文件下载

package com.sinux.cc.fileuploadanddownload;

import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * 文件下载工具类
 */
public class FileDownload {
    /**
     * @param response
     * @param filePath 文件完整路径包括:文件完整名,扩展名
     */
    public static void fileDownLoad(HttpServletResponse response, String filePath) {
        OutputStream os = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            String fileName = file.getName();
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            //解决中文乱码
            String fileNameStr = new String(fileName.getBytes("utf-8"), "ISO8859-1");
            response.setHeader("Location", fileNameStr);
            response.setHeader("Content-Disposition", "attachment;filename=" + fileNameStr);
            os = response.getOutputStream();
            download(os, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private static void download(OutputStream os, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            int BUFFERSIZE = 2 << 10;
            int length = 0;
            byte[] buffer = new byte[BUFFERSIZE];
            while ((length = is.read(buffer, 0, BUFFERSIZE)) >= 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 浏览器下载
     */
    public static void download(InputStream in, String fileName) {
        HttpServletResponse res =
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();


        try {
            res.reset();
            res.setCharacterEncoding("utf-8");
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + fileName);

        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        BufferedInputStream bi = null;
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            bi = new BufferedInputStream(in);
            int i = bi.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, buffer.length);

                i = bi.read(buffer);
            }
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bi) {
                try {
                    bi.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值