1. 程式人生 > >基於springMVC的檔案上傳(親自實踐,完美的執行)

基於springMVC的檔案上傳(親自實踐,完美的執行)

由於是一個新手菜鳥,所以說對很多東西都不是很瞭解,最近剛好在做一個專案需要做檔案的上傳和下載,以前直接是用寫好的,這個自己動手寫了一下用了半天時間跟大家分享一下。

一.環境是SSM+Maven

      首先,你需要搭建好springMC的環境,如果不會搭建的話請自己百度,他會告訴你的。

二.匯入需要的Jar包

因為這個附件的上傳和下載是基於SpringMVC做的,因此我們需要匯入一下jar包。如下,我直接在pom中引入就可以了。

		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>

三.接下來比較重要了,就是需要去配置下你的springMVC的配置檔案,配置資訊如下。

			<bean id="multipartResolver"  
			        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
			        <!-- 上傳檔案大小上限,單位為位元組(10MB) -->
			        <property name="maxUploadSize">  
			            <value>10485760</value>  
			        </property>  
			        <property name="defaultEncoding">
			            <value>UTF-8</value>
			        </property>
			    </bean>

四。接下來就是寫html介面(最重要的一點是一定要在form中加上 enctype="multipart/form-data" )

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>檔案上傳</h3>
	<form enctype="multipart/form-data"  action="http://localhost:8080/yangfan-server/upload" method="post" >  
	    <input type="file" name="file" id="file"/>  
	    引數inputStr:<input type="text" name="des">    
	        <input type="submit" value="submit" />  
	</form>  
	<hr/>
	
	<h3>檔案下載</h3>
		<a href="download?filename=50769870/Desert.jpg">
		  Penguins.jpg
		</a>
</body>
</html>

五.接下來就是controller的實現

這個是檔案上傳的,因為我自己寫了一個方法來生成一個隨機的路徑,你們也可以自己定義自己的路徑。

//上傳檔案會自動繫結到MultipartFile中
    @RequestMapping(value="/upload",method={RequestMethod.POST})
    public Result upload(HttpServletRequest request,
           @RequestParam("des") String des,
           @RequestParam("file") MultipartFile file) throws Exception {
    	
    	Result result = new Result();
       System.out.println(des);
       //如果檔案不為空,寫入上傳路徑
       if(!file.isEmpty()) {
    	   long uuid = NumberUtil.createId();
    	   //上傳檔案路徑
    	   String path = request.getServletContext().getRealPath("/images/") + File.separator + uuid;
           //上傳檔名 
           String filename = file.getOriginalFilename();
           File filepath = new File(path,filename);
           //判斷路徑是否存在,如果不存在就建立一個
           if (!filepath.getParentFile().exists()) { 
               filepath.getParentFile().mkdirs();
           }
           //將上傳檔案儲存到一個目標檔案當中
           file.transferTo(new File(path + File.separator +filename));
           result.setSuccess(true);
           result.addDefaultModel("fileName", "fileName");
           result.addDefaultModel("fileDownLoad",uuid+"/"+filename);
           return result;
       } else {
           return result;
       }

    }
    

這個是下載的deomo

 @RequestMapping(value="/download",method={RequestMethod.POST,RequestMethod.GET})
    public ResponseEntity<byte[]> download(HttpServletRequest request,
            @RequestParam("filename") String filename,
            Model model)throws Exception {
       //下載檔案路徑
       String path = request.getServletContext().getRealPath("/images/");
       File file = new File(path + File.separator + filename);
       HttpHeaders headers = new HttpHeaders();  
       //下載顯示的檔名,解決中文名稱亂碼問題  
       String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
       String[] strArr = downloadFielName.split("/");
       //通知瀏覽器以attachment(下載方式)開啟圖片
       headers.setContentDispositionFormData("attachment", strArr[1]); 
       //application/octet-stream : 二進位制流資料(最常見的檔案下載)。
       headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
       return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
               headers, HttpStatus.CREATED);  
    }


以上就是上傳和下載的程式碼了,不過現在只是上傳單個檔案的,後續會加上多個檔案的批量操作的。

歡迎轉載,請註明出處1