搭建SpringMvc開發環境web
導入包:spring
commons-fileupload-1.2.1.jarsession
commons-io-2.0.jarapp
配置文件上傳解析器dom
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--上傳文件的最大大小> <property name="maxUploadSize" value="17367648787"></property>
<!-- 上傳文件的編碼 --> <property name="defaultEncoding" value="UTF-8"></property> </bean>
上傳頁面post
<a href="down">下載圖片</a>
<form action="up" method="post" enctype="multipart/form-data">
頭像:<input type="file" name="uploadFile" />
描述:<input type="text" name="desc" />
<input type="submit" value="上傳" />
</form>編碼
控制器方法.net
@Controller
public class TestUploadAndDownController {orm
@RequestMapping("/down")
public ResponseEntity<byte[]> down(HttpSession session) throws IOException{
//獲取下載文件的路徑
String realPath = session.getServletContext().getRealPath("img");
String finalPath = realPath + File.separator + "2.jpg";
InputStream is = new FileInputStream(finalPath);
//available():獲取輸入流所讀取的文件的最大字節數
byte[] b = new byte[is.available()];
is.read(b);
//設置請求頭
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=zzz.jpg");
//設置響應狀態
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(b, headers, statusCode);
return entity;
}
@RequestMapping(value="/up", method=RequestMethod.POST)
public String up(String desc, MultipartFile uploadFile, HttpSession session) throws IOException {
//獲取上傳文件的名稱
String fileName = uploadFile.getOriginalFilename();
String finalFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
String path = session.getServletContext().getRealPath("photo") + File.separator + finalFileName;
File file = new File(path);
uploadFile.transferTo(file);
return "success";
}
@RequestMapping(value="/up_old", method=RequestMethod.POST)
public String up_old(String desc, MultipartFile uploadFile, HttpSession session) throws IOException {
//獲取上傳文件的名稱
String fileName = uploadFile.getOriginalFilename();
String path = session.getServletContext().getRealPath("photo") + File.separator + fileName;
//獲取輸入流
InputStream is = uploadFile.getInputStream();
//獲取輸出流
File file = new File(path);
OutputStream os = new FileOutputStream(file);
/*int i = 0;
while((i = is.read()) != -1) {
os.write(i);
}*/
/*int i = 0;
byte[] b = new byte[1024];
while((i = is.read(b)) != -1) {
os.write(b, 0, i);
}*/
os.close();
is.close();
return "success";
}
}圖片