html5圖片上傳【文件上傳】,在網(wǎng)上找了很多資料,主要也就2種
1.from表單提交的方式
<form action="pushUserIcon" method="post" enctype="multipart/form-data"> <table> <tr> <td width="50" align=left>圖片:</td> <td><input type="file" name="file"/></td> </tr> <tr> <td width="50" align="left">用戶(hù)id:</td> <td><input type="text" name="userId"/></td> </tr> <tr> <td><input type="submit"> </td> </tr> </table> </form>
注意: enctype="multipart/form-data" 必須要填
1.1.Java頁(yè)面直接提交:
@RequestMapping(value="/pushUserIcon",method=RequestMethod.POST) @ResponseBody public String pushUserIcon(HttpServletRequest request, HttpServletResponse response) throws IOException,BaseException { String result = null; String userId = request.getParameter("userId"); try{ //轉(zhuǎn)型為MultipartHttpRequest(重點(diǎn)的所在) MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //獲得第1張圖片(根據(jù)前臺(tái)的name名稱(chēng)得到上傳的文件) MultipartFile file = multipartRequest.getFile("file"); result = uploadImageServic.uploadFile(file, request, userId); System.out.println("result:" + result); response.setContentType("text/html;charset=utf8"); response.getWriter().write("result:" + result); }catch(Exception e){ BaseException baseException = new BaseException(e); baseException.setErrorMsg("Upload API Exception"); throw baseException; } return null; }
1.2.原生js 和jQuery的網(wǎng)上有很多,這里就不多說(shuō)了。
1.2.1. fromData創(chuàng)建的兩種方式
var formData = new FormData($("#myForm")[0]);//用form 表單直接 構(gòu)造formData 對(duì)象; 就不需要下面的append 方法來(lái)為表單進(jìn)行賦值了。 //var formData = new FormData();//構(gòu)造空對(duì)象,下面用append 方法賦值。 // formData.append("policy", ""); // formData.append("signature", ""); // formData.append("file", $("#file_upload")[0].files[0]);
2.不用from表單提交:
<table style="border: 1px solid black; width: 100%"> <tr> <td width="50" align=left>圖片:</td> <td><input type="file" id="imageFile" name="img" multiple="multiple"/></td> <td> <input type="button" value="調(diào)用" onclick="pushImg()" /> </td> </tr> </table>
HTML就這些,我想大家應(yīng)該都能看懂,下面就要說(shuō)說(shuō)這2種提交方式,Ajax是如何編碼?【from表單提交方式也可以使用js或者直接提交頁(yè)面刷新】
Ajax編碼也有2種:
1.原生js
function sub() { var file = document.getElementById("imageFile"); var files = file.files; for(var i = 0 ; i < files.length;i++) { uploadFile(files[i]); } } var xhr = null; function uploadFile(file) { xhr = new XMLHttpRequest(); /* xhr.addEventListener("error", uploadFailed, false); xhr.addEventListener("abort", uploadCanceled, false); */ xhr.open("post", "upload/", true); //訪問(wèn)控制器是upload,后面必須加'/'否則會(huì)報(bào)錯(cuò)"org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.Mult...",但是如果是多級(jí)的URL【例如XX/XXX/00/upload/0】又沒(méi)問(wèn)題了. var fd = new FormData(); fd.append("userID", "1"); fd.append("errDeviceType", "001"); fd.append("errDeviceID", "11761b4a-57bf-11e5-aee9-005056ad65af"); fd.append("errType", "001"); fd.append("errContent", "XXXXXX"); fd.append("errPic", file); xhr.send(fd); xhr.onreadystatechange = cb; } function cb() { if(xhr.status == 200) { var b = xhr.responseText; if(b == "success"){ alert("上傳成功!"); }else{ alert("上傳失?。?quot;); } } }
2.jquery
function pushImg(obj) { debugger; var url = "upload/"; //訪問(wèn)控制器是upload,后面必須加'/'否則會(huì)報(bào)錯(cuò)"org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.Mult...",但是如果是多級(jí)的URL【例如XX/XXX/00/upload/0】又沒(méi)問(wèn)題了. var param = $("#errorParameter").val(); var files = $("#imageFile").get(0).files[0]; //獲取file控件中的內(nèi)容 var fd = new FormData(); fd.append("userID", "1"); fd.append("errDeviceType", "001"); fd.append("errDeviceID", "11761b4a-57bf-11e5-aee9-005056ad65af"); fd.append("errType", "001"); fd.append("errContent", "XXXXXX"); fd.append("errPic", files); $.ajax({ type: "POST", contentType:false, //必須false才會(huì)避開(kāi)jQuery對(duì) formdata 的默認(rèn)處理 , XMLHttpRequest會(huì)對(duì) formdata 進(jìn)行正確的處理 processData: false, //必須false才會(huì)自動(dòng)加上正確的Content-Type url: url, data: fd, success: function (msg) { debugger; var jsonString = JSON.stringify(msg); $("#txtTd").text(jsonString) alert(jsonString); }, error: function (msg) { debugger; alert("error"); } }); }
現(xiàn)在前端的就應(yīng)該差不多了,現(xiàn)在就是接口了,我的參數(shù)和訪問(wèn)路徑都好了,現(xiàn)在就差接口服務(wù)了:
spring mvc框架:
@RequestMapping(value = { "upload" }) public void pushErrorData(HttpServletRequest request, HttpServletResponse response) throws BaseException { String userID=request.getParameter("userID"); // 轉(zhuǎn)型為MultipartHttpRequest(重點(diǎn)的所在)這個(gè)就是上面ajax中提到如果直接訪問(wèn)此接口而不加"/",此轉(zhuǎn)型就會(huì)報(bào)錯(cuò) MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; //MultipartFile file = multipartRequest.getFiles("errPic");//獲取文件集合 對(duì)應(yīng) jquery $("#imageFile").get(0).files // 獲得第1張圖片(根據(jù)前臺(tái)的name名稱(chēng)得到上傳的文件) MultipartFile file = multipartRequest.getFile("errPic"); //對(duì)應(yīng) jquery $("#imageFile").get(0).files[index] Map<String, Object> map = new HashMap<String, Object>(); if (null!=file && !file.isEmpty()) { try { map = Common.uploadFile(file); } catch (IOException e) { BaseException baseException = new BaseException(e); //baseException.setErrorMsg(imgErrorMsg); throw baseException; } } } /** * 圖片上傳 * * @param file * @return * @throws IOException * @throws BaseException */ public static Map<String, Object> uploadFile(MultipartFile file) throws IOException, BaseException { String fail = ConfigBundleHelper.getValue("busConfig", "fail");//上傳失敗狀態(tài) String success = ConfigBundleHelper.getValue("busConfig", "success");//上傳成功狀態(tài) String errorMsg = ConfigBundleHelper.getValue("busConfig","imgErrorMsg");//上傳錯(cuò)誤信息 String filePath = ConfigBundleHelper.getValue("busConfig", "filePath");//上傳路徑,本來(lái)是相對(duì)路徑,但是在發(fā)布后路徑會(huì)創(chuàng)建在tomcat的bin目錄下,所以接口上傳的路徑是一個(gè)難題,我用的是絕對(duì)路徑,等到發(fā)布到Linux環(huán)境中,通過(guò)配置文件修改路徑為L(zhǎng)inux中的資源地址【防止工程刪除而資源文件不會(huì)丟失】,然后重新發(fā)布工程時(shí)再通過(guò)Linux的命令把我們需要的資源文件導(dǎo)入到我們發(fā)布的工程項(xiàng)目中。 String size = ConfigBundleHelper.getValue("busConfig", "fileSize"); String interfaceService = ConfigBundleHelper.getValue("busConfig", "interfaceService"); long maxFileSize = (Integer.valueOf(size)) * 1024 * 1024; String suffix = file.getOriginalFilename().substring( file.getOriginalFilename().lastIndexOf(".")); long fileSize = file.getSize(); Map<String, Object> map = new HashMap<String, Object>(); if (suffix.equals(".png") || suffix.equals(".jpg")) { if (fileSize < maxFileSize) { // System.out.println("fileSize"+fileSize); String fileName = file.getOriginalFilename(); fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); File tempFile = new File(filePath, new Date().getTime() + fileName); try { if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs();//如果是多級(jí)文件使用mkdirs();如果就一層級(jí)的話,可以使用mkdir() } if (!tempFile.exists()) { tempFile.createNewFile(); } file.transferTo(tempFile); } catch (IllegalStateException e) { BaseException baseException = new BaseException(e); baseException.setErrorMsg(errorMsg); throw baseException; } map.put("SUCESS", success); map.put("data",interfaceService + filePath + new Date().getTime() + tempFile.getName()); } else { map.put("SUCESS", fail); map.put("data", "Image too big"); } } else { map.put("SUCESS", fail); map.put("data", "Image format error"); } return map; }
這是我在工作中所遇到到問(wèn)題,分享給大家,希望大家不會(huì)在這個(gè)問(wèn)題上花費(fèi)大量的時(shí)間。謝謝