SpringBoot上傳下載檔案
阿新 • • 發佈:2019-01-04
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> 使用Intellij IDEA生成預設SpringBoot專案不含webapp資料夾,如果沒有找到webapp,
request.getSession().getServletContext().getRealPath("/") 獲取到的是C盤的臨時目錄建立在src/main下建立webapp即可解決
一,設定上傳檔案大小
可以在啟動類中建立如下方法配置上傳大小
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory multipartConfigFactory = new MultipartConfigFactory();
multipartConfigFactory.setMaxFileSize("24MB");
multipartConfigFactory.setMaxRequestSize("20MB");
return multipartConfigFactory.createMultipartConfig();
}
必須在類上面新增@Configuration
二,controller中方法
1,上傳
@PostMapping(value = "/upload")
public @ResponseBody String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
String contentType = file.getContentType();
String fileName = file.getOriginalFilename();
System.out.println(fileName);
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\";
System.out.println(filePath);
if (!file.isEmpty()){
File targetFile = new File(filePath + fileName);
if (!targetFile.exists()){
targetFile.createNewFile();
}
file.transferTo(targetFile);
}
return "upload success";
}
2.,下載
@RequestMapping(value = "/download",method = RequestMethod.GET)
public ResponseEntity<byte[]> dowonload(HttpServletRequest request) throws IOException {
String path = request.getSession().getServletContext().getRealPath("/") + "upload\\";
File file = new File(path + "/symbol-check.png");
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment","symbol-check.png");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
3,前臺
<form id="fileForm" name="fileForm" enctype="multipart/form-data">
<input type="file" name="file" id="file"/>
<button id="btn" type="button">提交</button>
</form>
<a href="download">下載</a>
$(function () {
$("#btn").click(function () {
$.ajax({
type: "POST",
url: "upload",
contentType: false,
processData: false,
data: new FormData($("#fileForm")[0]),
success: function (data) {
alert(data)
}
});
});
});