最近在做開發的時候,碰到需要做個圖片上傳的功能,原先使用的是submit提交,但是這樣會導致處理上的一些失誤。如:前臺頁面的信息已經提示,但是其實後臺還未完成程序的運轉。
後來請教了同事,學會了使用ajax的圖片上傳提交方法,記錄銘記之。
首先要下載ajaxfileupload.js。
然後前臺只要做 以下操作就可以完成ajax的圖片上傳
var id = new Array();
id.push("appIconLittle");
id.push("appIconBig");
$.ajaxFileUpload({
url : '${ctx}/apply/doSave',
secureuri : false,
fileElementId : id,
data : {
'appNameCn' : $("#appNameCn").val(),
'appNameEn' : $("#appNameEn").val(),
'cityCodes' : $("#cityCodes").val(),
'parent_id' : $("#parent_id").val(),
'hasLight' : $("#hasLight").val(),
'appContKind' : $("#appContKind").val(),
'appUrl' : $("#appUrl").val(),
'appVersion' : $("#appVersion").val(),
'isIframe' : $("#isIframe").val(),
'appDesc' : $("#appDesc").val(),
'appPartners' : $("#appPartners").val(),
'kernelApply' : $("#kernelApply").val(),
'provinceApply' : $("#provinceApply").val(),
'coreIds' : $("#coreIds").val()
},
dataType : 'json',
success : function(data, status) {
art.dialog({
content: data.msg,
time: 3000,
beforeunload: function () {
if(parentWin != null)
parentWin.goto_query();
closeWin();
}
});
},
error : function(data, status, e) {
}
})
當頁面有多個圖片進行上傳的時候,可以在javascrpit中new Array()來存儲多個id值,提交方式可以選擇get或者post,get提交的時候,如果遇到中文亂碼,
在前臺可以使用如:
function clickPlace(){
var place = $("#place").val()
window.location.href="${ctx}/trainResells_web.do?&siteId=${siteId}&belongsarea="+encodeURI(encodeURI(place));
}
後臺使用String belongsarea = URLDecoder.decode(request.getParameter("belongsarea"), "UTF-8");進行轉碼。
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg","添加成功");
try {
response.setContentType("text/html;charset=GBK");
PrintWriter writer = response.getWriter();
writer.write(jsonObject.toJSONString());
} catch (IOException e) {
e.printStackTrace();
}
後臺以JSON格式返回。
以下順便附上上傳完之後顯示圖片的代碼
前臺
<div id="showLettleImg" style="position:fixed;display:none;left: 200px;top=-5px;" ><img οnclick="show(2)" src="${ctx}/apply/image?appId=${apply.appId}&str=lettle" />
後臺
@RequestMapping("/image")
public void image(HttpServletRequest request, HttpServletResponse response,Long appId,String str){
Apply apply = applyService.get(appId);
ServletOutputStream outputStream = null;
try {
Blob img = null;
if(("lettle").equals(str)){
img = apply.getAppIconLittle();
}
if(("big").equals(str)){
img = apply.getAppIconBig();
}
byte[] by = new byte[1024];
InputStream input = img.getBinaryStream();
response.setContentType("text/img");
outputStream = response.getOutputStream();
int count = -1;
while((count = input.read(by,0,1024)) != -1) {
outputStream.write(by, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}