这是前端的部分代码
function uploadImage(){
$.ajax({
type:'post',
url:'UploadImage',
data:{image:img},
async:false,
datatype:'json',
success:function(data){
if(data.success){
alret('上传成功');
}else{
alret('上传失败');
}
},
error:function(err){
alert('网络故障');
}
});
}
这是后台代码
String image = request.getParameter("image");
String header = "data:image/jpeg;base64";
image = image.substring(header.length());
BASE64Decoder decoder = new BASE64Decoder();
try{
byte[] b = decoder.decodeBuffer(image);
String imageFilePath = "D://"+"222"+".jpg";
OutputStream out = new FileOutputStream(imageFilePath);
out.write(b);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
前端的“success”应该是类似于信息提示框,但后台的判定应该怎么写我一直没有搞清楚,也就是“if(data.success)”响应后台的什么信息?
后台没有return 么
后台代码需要返回一个json字符串,后台在文件上传失败时,需要定义个map,map里的success设置为false,成功设置为true,然后把map生成json
后台的ajax要return一个值,然后前台不能直接用,需要json_decode
输出json格式字符串,如
try{
byte[] b = decoder.decodeBuffer(image);
String imageFilePath = "D://"+"222"+".jpg";
OutputStream out = new FileOutputStream(imageFilePath);
out.write(b);
out.flush();
out.close();
////////////////////////////
response.getWriter().write("{\"success\":true}");
}catch(Exception e){
e.printStackTrace();
}
后台代码需要返回一个json字符串,然后return
既然用ajax上传,那么回调就要返回json。既然是用的servlet,那就不建议使用ajax,直接form提交上传吧
后台返回的json中应该包含名为“success”的key值,前端取值的时候data.success就等于用success这个key去取到json对应的值,来判定是否成功
public Map functions{
Map map=new HashMap();
try{
byte[] b = decoder.decodeBuffer(image);
String imageFilePath = "D://"+"222"+".jpg";
OutputStream out = new FileOutputStream(imageFilePath);
out.write(b);
out.flush();
out.close();
map.put("success",true);
}catch(Exception e){
map.put("success",false);
// e.printStackTrace();
}
return map
}
后台代码需要返回一个json字符串的,然后return
datatype:'json',
success:function(data){//返回格式为json
if(data.success){//判定返回的data属性是否为success如成功则上传成功
alret('上传成功');
}else{
alret('上传失败');
}
},
后台不是应该返回一个Response么?