文件上傳我使用的是jquery的一個插件"ajaxfileupload.js",使用方式詳見下面的一種方式,使用file類型的input,同時需要給button綁定事件,這邊使用的"ajaxfileupload.js"當中定義的ajax請求,到后台。
<div id="fileupload"> <input type="file" id="file" name="file" /> <input type="button" id="upload" value="上傳文件" /> </div>
<script type="text/javascript" src="<%=path%>/js/jquery/jquery-1.5.1.js"></script> <script type="text/javascript" src="<%=path%>/js/accnet/common/ajaxfileupload.js"></script>
//文件上傳 $(function() { $("#upload").click(ajaxFileUpload); }); function ajaxFileUpload() { var url = "/spare/flow.spr?"; var method = "method=fileUpload" $.ajaxFileUpload({ url : contextPath + url + method, secureuri : false, fileElementId : 'file', dataType : 'text', success : function(data, status) { if (data == "exist") { alert("該文件已經存在請勿重復上傳"); } if (data == "success") { alert("文件上傳成功"); } if (data == "fail") { alert("文件上傳失敗,請重新上傳"); } }, error : function() { } }); }
后台當中的代碼使用的是Spring 的mvc框架。
使用MultipartFile的時候還需要在xml文件當中進行配置
<!-- 配置MultipartResolver 用於文件上傳 使用spring的CommosMultipartResolver --> <beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5400000" p:uploadTempDir="fileUpload/temp" > </beans:bean>
其中屬性詳解:
defaultEncoding="UTF-8" 是請求的編碼格式,默認為iso-8859-1
maxUploadSize="5400000" 是上傳文件的大小,單位為字節
uploadTempDir="fileUpload/temp" 為上傳文件的臨時路徑
1 @RequestMapping(params = "method=fileUpload") 2 public void fileUpload( 3 @RequestParam(value = "file", required = false) MultipartFile file, 4 HttpServletRequest request, HttpServletResponse response) { 5 String path = request.getSession().getServletContext() 6 .getRealPath("upload"); 7 String fileName = file.getOriginalFilename(); 8 File targetFile = new File(path, fileName); 9 //設置文件保存的路徑 提供給后面的解析使用 10 request.getSession().setAttribute("fileNameSpare", fileName); 11 request.getSession().setAttribute("filePathSpare", path); 12 if (targetFile.exists()) { 13 super.flushResponse(response, "exist"); 14 } else { 15 try { 16 file.transferTo(targetFile); 17 super.flushResponse(response, "success"); 18 } catch (Exception e) { 19 logger.error(e.getMessage()); 20 super.flushResponse(response, "fail"); 21 } 22 }
23 }
下面是關於MultipartFile方法的一些介紹,圖片來自Spring官網的一些介紹
1.getBytes() 以二進制數組返回文件的內容
2.getContentType() 以String類型返回文件的內容,該方法存在一定的歧義,我沒有嘗試過,像那種圖片,word文件類型的數據不知這邊是如何處理的
3.getInputStream() 獲得輸入流
4.getName() 獲取表單中文件組件的名字
5.getOriginalFilename()獲得在客戶端文件系統當中初始化的名稱
6.getSize() 獲得文件的大小
7.isEmpty() 判斷文件是否為空
8.transferTo() 轉換成文件
附上Spring的官方API文檔
https://docs.spring.io/spring/docs/1.2.x/javadoc-api/org/springframework/web/multipart/MultipartFile.html