html代码:
<input type="file" id="imgFile" name="imgFile" />
js代码:
function uploadImg(cookbookId){
var cbId = cookbookId;
$.ajaxFileUpload({
url:'${web.context.path}/restaurant/uploadCookbookImg.action', //上传文件的服务端
secureuri:false, //是否启用安全提交
dataType: 'text', //数据类型
data:{'cookbookId':cbId,},
fileElementId:'imgFile', //表示文件域ID
//提交成功后处理函数
success: function(data){
var arr = new Array();
arr = data.split("success");
if(arr.length != 1){
alert("图片上传成功!");
}
},
//提交失败处理函数
error: function (data){
alert("上传图片失败!");
}
});
}
java代码:
public String uploadCookbookImg() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String nowDate = sdf.format(new Date());
String path = "/data/webserver/lifeMap/foodImg/" + nowDate + "/";
Long l = System.currentTimeMillis();
fileName = "CBF" + l.toString() + ".jpg";
if(null != file){
File saveFile = new File(new File(path),fileName);
if (!saveFile.getParentFile().exists()){
saveFile.getParentFile().mkdirs();
}
FileUtils.copyFile(file, saveFile);
}
} catch (Exception e) {
e.printStackTrace();
}
return "uploadCookbookImg";
}