天天看點

SpringBoot的檔案下載下傳

SpringBoot的檔案下載下傳方法有很多,此處隻記錄使用Spring的Resource實作類FileSystemResource做下載下傳,其餘實作類照葫蘆畫瓢即可。

直接上幹貨

1、下載下傳部分代碼

public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new FileSystemResource(file));
    }
           

這段代碼,我是封裝在BaseController.class,其他的Controller繼承該類,就可直接調用父類的下載下傳方法,service隻需要提供檔案file即可。

2、執行個體展示

@RestController
@RequestMapping(value = "/order", method = RequestMethod.POST)
public class OrderController extends BaseController {

    @Autowired
    private IOrderService orderService;

    @RequestMapping(value = "/export")
    public ResponseEntity<FileSystemResource> listExport(String proNo) {
        File file = orderService.listExport(proNo);
        return export(file);
    }
    }
           

注意:此處使用的下載下傳傳回是FileSystemResource,是以service提供的是File。

以下是百度到的Resource其它實作類,引用來自http://elim.iteye.com/blog/2016305

ClassPathResource 可用來擷取類路徑下的資源檔案。假設我們有一個資源檔案test.txt在類路徑下,我們就可以通過給定對應資源檔案在類路徑下的路徑path來擷取它,new ClassPathResource(“test.txt”)。

FileSystemResource可用來擷取檔案系統裡面的資源。我們可以通過對應資源檔案的檔案路徑來建構一個FileSystemResource。FileSystemResource還可以往對應的資源檔案裡面寫内容,當然前提是目前資源檔案是可寫的,這可以通過其isWritable()方法來判斷。FileSystemResource對外開放了對應資源檔案的輸出流,可以通過getOutputStream()方法擷取到。

UrlResource可用來代表URL對應的資源,它對URL做了一個簡單的封裝。通過給定一個URL位址,我們就能建構一個UrlResource。

ByteArrayResource是針對于位元組數組封裝的資源,它的建構需要一個位元組數組。

ServletContextResource是針對于ServletContext封裝的資源,用于通路ServletContext環境下的資源。ServletContextResource持有一個ServletContext的引用,其底層是通過ServletContext的getResource()方法和getResourceAsStream()方法來擷取資源的。

InputStreamResource是針對于輸入流封裝的資源,它的建構需要一個輸入流。

繼續閱讀