1.首先,引入
"jquery-form.js"文件
<script type="text/javascript"
src="jquery-form.js"></script>
src="jquery-form.js"></script>
2.把添加图片的按钮放在form表单中
<form id="uploadImageForm" name="uploadImageForm" action=""
enctype="multipart/form-data" method="post" data-ajax="false">
<input id="image" type="file" accept="image.png,image.gif,image.jpg"
name="
image" multiple="multiple"/>
</form>
<image id="
showImage"/ >
showImage
3.表单
ajaxSubmit形式提交(ajaxSubmit这个函数是jquery-form.js中的)
$("#
image").on('change',function() {
var options = {
url:'url',
dataType : 'json',
contentType : "application/json; charset=utf-8",
success : function(data) {
console.log(data);
//换一张图片显示
var path="${contextPath}"+data;
$("#showImage").attr("src", path);
}
};
// 提交表单
$('#uploadImageForm').ajaxSubmit(options);
})
public void uploadImage(){
// 设置上传路径
String path_tmp = "";
String uploadDir = File.separator + "image";
path_tmp = PathKit.getWebRootPath() + uploadDir;
// 文件上传 ,'resume'为表单字段名称
UploadFile uploadFile = getFile("
image", path_tmp);//这里获得的是空
String fileExtName = uploadFile.getFileName().substring(uploadFile.getFileName().lastIndexOf("."));
String newFileName = System.currentTimeMillis() + fileExtName;
String newFilePath = path_tmp + "/"+ newFileName;
uploadFile.getFile().renameTo(new File(newFilePath));
//要返回图片的地址
String imagePath=uploadDir+"\\"+newFileName;
Gson s = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String jsonString = s.toJson(imagePath);
renderJson(jsonString);
}