天天看點

SpringBoot關于檔案下載下傳和上傳

public class UploadFileUtils{
    private static String PATH=null;

    static {
        try {
            PATH= ResourceUtils.getURL("classpath:").getPath() + "/static/";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * description:
     *        傳入檔案夾名和檔案,儲存至那個檔案夾
     * @param directoryName 需要上傳到哪個檔案家
     * @param uploads 上傳的檔案
     * @return int 傳回上傳成功的條數
     */
    public static void upload(String directoryName, MultipartFile[] uploads,List<String> fileList) throws IOException {

        String path = PATH + directoryName;
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        int flag=0;
        for (MultipartFile upload : uploads) {
            String filename=fileList.get(flag++);
            upload.transferTo(new File(path, filename));
        };
    }



    /**
     * 
     *
     * @param directoryName   要儲存的檔案加
     * @param upload  下載下傳的檔案
     * @param fileName  需要儲存的檔案名
     * @return java.lang.String
     */
    public static String upload(String directoryName, MultipartFile upload,String fileName) throws IOException {
        String path = PATH + directoryName;
        File directory = new File(path);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        upload.transferTo(new File(path, fileName));
        return fileName;
    }

    //下載下傳
    public static void downloadFileAction(String path,HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            File file = new File(path);
            fis = new FileInputStream(file);
//            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
           

由于上傳限制預設是10M更大需要修改配置

spring:
  servlet:
    multipart:
      file-size-threshold: 100MB
      max-file-size: 10MB
      max-request-size: 100MB