標籤:ajax jersey 圖片上傳
近期的項目裡需要在前端上傳圖片後端接收處理。前端JSP頁面使用Ajax上傳圖片後端使用Jersey架構提供restful介面接收處理圖片。
一、前端的處理
jsp頁面中圖片上傳沒有使用form表單而是直接使用file類型的input控制項
<input type="file" name="file" class="inpTxtA" value="" id="appLogo"/><input class="inpTxtA" value="" id="appID"/>
js中使用ajax處理檔案上傳
var formData = new FormData();//使用formData來上傳資料 //content-Type是form-data類型formData.append("appId", $("#appID").val());formData.append("file", $("#appLogo")[0].files[0]);//取file類型input中的檔案$.ajax({method : "POST",url : "/apps/updateApp",timeout : 10000, //逾時時間設定單位毫秒crossDomain: true,async: false,headers: { "client-type":"platform"},dataType:"json",data: formData,contentType:false,//processData:false,//資料不做預先處理success : function(response) {alert(response.msg);return;},error : function(e) {alert(response.msg);return;}});
二、服務端處理
服務端使用jersey架構提供restful介面因為資料是以form-data的參數類型來傳遞的所以服務端介面中的參數類型要指定為@FormDataParam。
/**應用資訊更新*檔案以InputStream類型上傳*檔案描述資訊以FormDataContentDisposition對象封裝。*/@Path("updateApp")@POST@Consumes(MediaType.MULTIPART_FORM_DATA)public Response updateApp(@FormDataParam("file") InputStream inputStream ,@FormDataParam("file") FormDataContentDisposition cp ,@FormDataParam("appId")String appId){ String name = cp.getFileName(); try{ name = new String(name.getBytes("ISO-8859-1"),"UTF-8"); }catch(Exception e){ result.put("errcode", 1); result.put("msg", "應用表徵圖名稱異常"); return JSONUtil.toJSONResponse(result); } ...//進一步處理}
三、可能出現的異常
1、在開發過程中前端對FormData的封裝可能會出現問題提示invocation TypeError之類的異常。一般的原因是沒有添加這兩個參數
contentType:false,//processData:false,//資料不做預先處理
這兩個參數申明不對資料做預先處理。如果缺失那麼前端在封裝資料時會進行預先處理比如x-www-form-urlencoded會將參數封裝到url裡面對於formData類型的資料預先處理可能會出現封裝異常。
2、後端服務接收參數時如果沒有正確指定參數類型也可能會報如下異常
嚴重: A message body reader for Java class javax.servlet.http.HttpServletRequest, and Java type interface javax.servlet.http.HttpServletRequest, and MIME media type multipart/form-data;boundary=----WebKitFormBoundaryRJ7E8B7MDzDGjBHG was not found.The registered message body readers compatible with the MIME media type are:multipart/* -> com.sun.jersey.multipart.impl.MultiPartReaderServerSide*/* -> com.sun.jersey.core.impl.provider.entity.FormProvider com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider com.sun.jersey.core.impl.provider.entity.StringProvider
這是因為參數是以formData格式上傳的如果介面中不指定參數類型為@FormDataParam則會出現上述異常提示。
Jersey後端服務接收ajax前端的圖片上傳