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

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

java开发中上传下载,很多地方用。每次都去写的话会很麻烦。这里写一个通用方法,以后遇到了只要准备好对应参数,调方法即可。
这里引入的是

<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;
    }
 }

这里就是公共方法了。调用的时候,可以这样:(注意:这里的fileName只是纯名字,无后缀)

  @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();
                }
            }
        }
    }
}

这里提供了多种文件下载的方法:择其善者而用之

你可能感兴趣的:(java中的上传,下载,java)