前言
實現下載文件和上傳文件的功能。
一、文件下載
使用ResponseEntity實現下載文件的功能
@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws
IOException {
//獲取ServletContext對象
ServletContext servletContext = session.getServletContext();
//獲取服務器中文件的真實路徑
String realPath = servletContext.getRealPath("/static/img/1.jpg");
//創(chuàng)建輸入流
InputStream is = new FileInputStream(realPath);
//創(chuàng)建字節(jié)數組
byte[] bytes = new byte[is.available()];
//將流讀到字節(jié)數組中
is.read(bytes);
//創(chuàng)建HttpHeaders對象設置響應頭信息
MultiValueMap<String, String> headers = new HttpHeaders();
//設置要下載方式以及下載文件的名字
headers.add("Content-Disposition", "attachment;filename=1.jpg");
//設置響應狀態(tài)碼
HttpStatus statusCode = HttpStatus.OK;
//創(chuàng)建ResponseEntity對象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers,
statusCode);
//關閉輸入流
is.close();
return responseEntity;
}
二、文件上傳
文件上傳要求form表單的請求方式必須為post,并且添加屬性enctype=“multipart/form-data”
SpringMVC中將上傳的文件封裝到MultipartFile對象中,通過此對象可以獲取文件相關信息。
步驟:文章來源:http://www.zghlxwxcb.cn/news/detail-692844.html
- 添加依賴
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --
>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
- 在SpringMVC的配置文件中添加配置:
<!--必須通過文件解析器的解析才能將文件轉換為MultipartFile對象-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
- 控制器方法:
@RequestMapping("/testUp")
public String testUp(MultipartFile photo, HttpSession session) throws
IOException {
//獲取上傳的文件的文件名
String fileName = photo.getOriginalFilename();
//處理文件重名問題
String hzName = fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID().toString() + hzName;
//獲取服務器中photo目錄的路徑
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
if(!file.exists()){
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
//實現上傳功能
photo.transferTo(new File(finalPath));
return "success";
}
總結
以上就是springMVC文件上傳和下載的講解。文章來源地址http://www.zghlxwxcb.cn/news/detail-692844.html
到了這里,關于SpringMVC之文件上傳和下載的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!