MVC文件上傳與下載

1、spring-mvc.xml配置

bean中的id必須爲multipartResolver

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
         	<property name="maxUploadSize" value="1048576"></property>
         </bean>

2、表單上傳(MVC接受)

@RequestMapping("/doupload")
	public String doUpload(MultipartFile fileName,HttpSession session){
		boolean falg = upload(fileName,session);
		if(falg){
			return "redirect:doSuccess.do";
			
		}else{
			return "redirect:doError.do";
		}
	}

	private boolean upload(MultipartFile file,HttpSession session) {
		boolean flag = false;
		try{
			String fileName = file.getOriginalFilename();
			String sufName = fileName.substring(fileName.lastIndexOf("."));
			String proName = UUID.randomUUID().toString();
			String pathName = proName + sufName;
			File f = new File("H:\\image\\upload\\"+pathName);
			file.transferTo(f);
			flag = true;
			session.setAttribute("path", pathName);
		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}

3、ajax上傳(MVC接受)

@RequestMapping("/doAjaxUpload")
	@ResponseBody
	public String doAjaxUpload(@RequestParam MultipartFile file){
		boolean falg = upload(file);
		System.out.println(falg);
		if(falg){
			return "success";
		}else{
			return "error";
		}
		
	}

	private boolean upload(MultipartFile file) {
		System.out.println("001");
		boolean flag = false;
		try{
			String fileName = file.getOriginalFilename();
			String sufName = fileName.substring(fileName.lastIndexOf("."));
			String proName = UUID.randomUUID().toString();
			String fileImgName = proName + sufName;
			File f = new File("H:\\image\\upload\\"+fileImgName);
			file.transferTo(f);
			flag = true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}

4、ajax上傳  兩種方式

//ajax表單上傳 第一種
function doUpload(){
	$("#uploadFormId").ajaxSubmit({
		type:"post",
		url:"attachements/insertAttachement",
		dataType:"json",
		success:function(result){
		alert(result.message);
		findAttachments();
		}
	});
	return false;//防止表單重複提交的一種方式
}
//ajax表單上傳 第二種
$("#btn").click(function(){
		alert("click");
		var formData = new FormData($("#form")[0]);
		$.ajax({
			url:"${pageContext.request.contextPath }/ajax/doAjaxUpload.do",
			data:formData,
			cache:false,
			contentType:false,//告訴jQuery不要去設置請求頭
			processData:false,//告訴spring不要去處理髮送的數據
			success:function(data){
				if(data=="success"){
					alert("上傳成功!!!");
				}
			}
			
		})
	})

 mvc文件下載

@RequestMapping("/download")
	public ResponseEntity<byte[]> download(Integer id) throws Exception{
        //獲取Attachements對象
		Attachements  att =attachementsService.findAttById(id);
		byte[] by;
		FileInputStream in = new FileInputStream(att.getFilePath());//得到文件路徑 用IO流的形式將文件已字節形式存放到by字節數組中
		by = new byte[in.available()];
		in.read(by);
        //進行編碼與解碼
		String fileName = new String(att.getFileName().getBytes(),"ISO8859-1");
        //設置請求頭
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attachment;fileName="+fileName);
		ResponseEntity<byte[]> entity = new ResponseEntity<>(by, headers, HttpStatus.OK);
		return entity;
	}

需要導入的依賴

<dependency>
	    <groupId>commons-fileupload</groupId>
	    <artifactId>commons-fileupload</artifactId>
	    <version>1.2.2</version>
	</dependency>
	<dependency>
	    <groupId>commons-io</groupId>
	    <artifactId>commons-io</artifactId>
	    <version>2.4</version>
	</dependency>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章