1. 程式人生 > >SpringMVC筆記(五)文件的上傳下載

SpringMVC筆記(五)文件的上傳下載

value comm mkdir -1 des tostring app available tip

一、SpringMVC實現文件的上傳

Spring MVC 上下文中默認沒有為文件上傳提供了直接的支持,因 此默認情況下不能處理文件的上傳工作,

如果想使用 Spring 的文件上傳功能,需現在上下文中配置 CommonsMultipartResovler:

二、文件上傳的步驟:
1.加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar

2.在SpringMVC配置文件中配置CommonsMultipartResovler

<!-- 配置文件上傳 -->
	<bean  id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	   <property name="defaultEncoding" value="utf-8"></property>
	   <property name="maxUploadSize" value="1024000"></property>
	</bean>

3.前端表單:註意:需要請求方式:POST,input類型:file,屬性:enctype="multipart/form-data"

 <form action="${pageContext.request.contextPath }/testUpload" method="post" enctype="multipart/form-data">
     file:<input type="file" name="photo">
     desc:<input type="text" name="desc">
     <input type="submit" value="上傳">
  </form>

4.文件上傳方法的實現

	@RequestMapping("/testUpload")
	public String testUpload(HttpServletRequest request,@RequestParam(value="desc",required=false)String desc,@RequestParam("photo") CommonsMultipartFile file){
		ServletContext servletContext = request.getServletContext();
		String realPath = servletContext.getRealPath("/upload");
		File file1 = new File(realPath);
		if(!file1.exists()){
			file1.mkdir();
		}
		OutputStream out = null;
		InputStream in = null;
		//uuid_name.jpg
		String prefix = UUID.randomUUID().toString();
		prefix = prefix.replace("-","");
		String fileName = prefix+"_"+file.getOriginalFilename();
		System.out.println(fileName);
		try {
			out = new FileOutputStream(new File(realPath+"\\"+fileName));
			in = file.getInputStream();
			//創建一個緩沖區
			byte buffer[]=new byte[1024];
			//判斷輸入流中的數據是否已經對完
			int len=0;
			//循環將輸入流讀入到緩沖區中(len=in.read(buffer)>0)表示in裏面還有數據
			while((len=in.read(buffer))!=-1){
				//使用FileOutPutStream輸出流,將緩沖區的數據輸出到指定目錄文件
				out.write(buffer,0,len);	
			}
		} catch (Exception   e) {
			e.printStackTrace();
		}
		//關閉輸入流、輸出流
		try {
			out.close();
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return  "success";
	}

三、文件的下載

文件能上傳就能下載

1.用ResponseEntity<byte[]> 返回值完成文件下載:

@RequestMapping(value="/testDownLoad")
	public ResponseEntity<byte[]> testDonwLoad(HttpServletRequest request) throws Exception{
		ServletContext servletContext=request.getServletContext();
		String fileName="風吹麥浪.mp3";
		String realPath = servletContext.getRealPath("/WEB-INF/"+fileName);
		InputStream in=new FileInputStream(new File(realPath));
		byte [] body=new byte[in.available()];
		in.read(body);
		MultiValueMap<String, String> headers=new HttpHeaders();
		fileName=new String(fileName.getBytes("gbk"),"iso8859-1");
		headers.set("Content-Disposition", "attachment;filename="+fileName);
		HttpStatus status=HttpStatus.OK;
		ResponseEntity<byte []> responseEntity=new ResponseEntity<>(body, headers,status);
		in.close();
		return responseEntity;	
	}

SpringMVC筆記(五)文件的上傳下載