版權聲明:本文為博主原創文章,未經博主同意不得轉載。 https://blog.csdn.net/itmyhome/article/details/27976873
使用springMVC提供的CommonsMultipartFile類進行讀取文件
須要用到上傳文件的兩個jar包 commons-logging.jar、commons-io-xxx.jar1、在spring配置文件里配置文件上傳解析器
<!-- 文件上傳解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="utf-8"></property><property name="maxUploadSize" value="10485760000"></property><!-- 最大上傳文件大小 --><property name="maxInMemorySize" value="10960"></property>
</bean>
2、文件上傳頁面(index.jsp)
<!-- method必須為post 及enctype屬性-->
<form action="fileUpload.do" method="post" enctype="multipart/form-data"><input type="file" name="file"><input type="submit" value="上傳">
</form>
3、FileController類
@Controller
public class FileController{@RequestMapping("/fileUpload.do")public String fileUpload(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request,HttpServletResponse response){long startTime=System.currentTimeMillis(); //獲取開始時間if(!file.isEmpty()){try {//定義輸出流 將文件保存在D盤 file.getOriginalFilename()為獲得文件的名字 FileOutputStream os = new FileOutputStream("D:/"+file.getOriginalFilename());InputStream in = file.getInputStream();int b = 0;while((b=in.read())!=-1){ //讀取文件 os.write(b);}os.flush(); //關閉流 in.close();os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}long endTime=System.currentTimeMillis(); //獲取結束時間System.out.println("上傳文件共使用時間:"+(endTime-startTime));return "success";}
}
上傳了一個3.54M的PDF文件 共使用29132毫秒(以自己計算機實際為準)
上面計算了上傳文件所使用時間。目的為了和下篇還有一種上傳方法進行比較 看哪個效率更高
測試URL: ?http://localhost:8080/spring/
項目源代碼下載地址:http://download.csdn.net/detail/itmyhome/7447419