您的位置:首页 > Web前端 > JQuery

springMVC上传图片,使用jquery预览

2016-09-16 12:42 295 查看
首先在html加入代码:其中div用于显示上传后的图片预览

<form id="form" enctype="multipart/form-data">
upload image:
<input type="file" id="image_input" name="file" />
<a href="#" onclick="upload()">upload</a>
</form>
<div id="imgDiv"></div>


js代码如下:需要先引入jquery.form.js插件<script type="text/javascript" src="js/jquery-form.js"></script>使用ajaxSubmit

function upload() {
var imagePath = $("#image_input").val();
if (imagePath == "") {
alert("please upload image file");
return false;
}
var strExtension = imagePath.substr(imagePath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("please upload file that is a image");
return false;
}
$("#form").ajaxSubmit({
type : 'POST',
url : 'upload/image.do',
success : function(data) {
alert("上传成功");
$("#imgDiv").empty();
$("#imgDiv").html('<img src="'+data+'"/>');
$("#imgDiv").show();
},
error : function() {
alert("上传失败,请检查网络后重试");
}
});

}


服务器端代码:

package com.shop.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/upload/")
public class ImageUploadController {
/**
* upload image and return the image url
*
* @return
* @throws IOException
* @throws IllegalStateException
*/
@RequestMapping("image")
@ResponseBody
public String uploadImage(HttpServletRequest request,
HttpServletResponse response, HttpSession session,
@RequestParam(value = "file", required = true) MultipartFile file)
throws IllegalStateException, IOException {
String path = session.getServletContext().getRealPath([b]"/upload"[/b]);
System.out.println("real path: " + path);
String fileName = file.getOriginalFilename();
System.out.println("file name: " + fileName);
File targetFile = new File(path, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(targetFile);
String fileUrl = request.getContextPath() + "/upload/" + fileName;
return fileUrl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: