老薛主機做電影網(wǎng)站怎么在百度發(fā)布免費廣告
文章目錄
- 前言
- 一、文件下載
- 二、文件上傳
- 總結(jié)
前言
實現(xiàn)下載文件和上傳文件的功能。
一、文件下載
使用ResponseEntity實現(xiàn)下載文件的功能
@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é)數(shù)組
byte[] bytes = new byte[is.available()];
//將流讀到字節(jié)數(shù)組中
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對象中,通過此對象可以獲取文件相關信息。
步驟:
- 添加依賴
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --
>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
- 在SpringMVC的配置文件中添加配置:
<!--必須通過文件解析器的解析才能將文件轉(zhuǎn)換為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;
//實現(xiàn)上傳功能
photo.transferTo(new File(finalPath));
return "success";
}
總結(jié)
以上就是springMVC文件上傳和下載的講解。