最近在做开发的时候,碰到需要做个图片上传的功能,原先使用的是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();
}
}
}