1. 程式人生 > >Spring Boot 檔案上傳和下載

Spring Boot 檔案上傳和下載

前言:以前的專案中檔案上傳下載會寫大量程式碼來實現,但是在Spring Boot中,簡化了大量程式碼,上傳只需要2行程式碼即可

package com.demo.controller;

import com.demo.model.FileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Auther: MQS
 * @Date: 18/09/11 11:50
 * @Description:
 */
@RestController
@RequestMapping("/file")
public class FileController {
    //檔案上傳路徑
    private String folder = "F:/";

    /**
     * 檔案上傳
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping
    public FileInfo upload(MultipartFile file) throws Exception {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File(folder, System.currentTimeMillis()+".txt");
        file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
    }

    /**
     *  檔案下載
     * @param name
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/{name}")
    public void downLoad(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception{
        try (InputStream inputStream = new FileInputStream(new File(folder, name+".txt"));
             OutputStream outputStream = response.getOutputStream();){
            response.setContentType("application/x-download");
            //addHeader 可以修改檔案下載時的名稱
//            response.addHeader("Content-Disposition", "attachment;filename=test.txt");
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }

}

文中示例為上傳txt檔案,上傳其他型別檔案字尾名可以根據需要自行獲取,修改

下載程式碼裡的 inputStream 和 outputStream 寫在try 後面的括號裡 是java7 之後的新特性,可以自動關閉流