前台代碼
上傳圖片按鈕
<a href="javascript:void(0)" onclick="uploadPhoto()">選擇圖片</a>
隱藏的文件選擇器
<input type="file" id="photoFile" style="display: none;" onchange="upload()">
圖片預覽
<img id="preview_photo" src="" width="200px" height="200px">
去除圖片預覽未選擇時默認時的邊框
<style>
img[src=""],img:not([src]){
opacity:0;
}
</style>
JavaScript部分
<script>
function uploadPhoto() {
$("#photoFile").click();
}
/**
* 上傳圖片
*/
function upload() {
if ($("#photoFile").val() == '') {
return;
}
var formData = new FormData();
formData.append('photo', document.getElementById('photoFile').files[0]);
$.ajax({
url:"${pageContext.request.contextPath}/system/uploadPhoto",
type:"post",
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.type == "success") {
$("#preview_photo").attr("src", data.filepath+data.filename);
$("#productImg").val(data.filename);
} else {
alert(data.msg);
}
},
error:function(data) {
alert("上傳失敗")
}
});
}
</script>
后台代碼
/**
* 圖片上傳
* @param photo
* @param request
* @return
*/
@RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
@ResponseBody
public Map<String, String> uploadPhoto(MultipartFile photo, HttpServletRequest request) {
Map<String, String> ret = new HashMap<String, String>();
if (photo == null) {
ret.put("type", "error");
ret.put("msg", "選擇要上傳的文件!");
return ret;
}
if (photo.getSize() > 1024 * 1024 * 10) {
ret.put("type", "error");
ret.put("msg", "文件大小不能超過10M!");
return ret;
}
//獲取文件后綴
String suffix = photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf(".") + 1, photo.getOriginalFilename().length());
if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
ret.put("type", "error");
ret.put("msg", "請選擇jpg,jpeg,gif,png格式的圖片!");
return ret;
}
//獲取項目根目錄加上圖片目錄 webapp/static/imgages/upload/
String savePath = request.getSession().getServletContext().getRealPath("/") + "/static/images/upload/";
File savePathFile = new File(savePath);
if (!savePathFile.exists()) {
//若不存在該目錄,則創建目錄
savePathFile.mkdir();
}
String filename = new Date().getTime() + "." + suffix;
try {
//將文件保存指定目錄
photo.transferTo(new File(savePath + filename));
} catch (Exception e) {
ret.put("type", "error");
ret.put("msg", "保存文件異常!");
e.printStackTrace();
return ret;
}
ret.put("type", "success");
ret.put("msg", "上傳圖片成功!");
ret.put("filepath", request.getSession().getServletContext().getContextPath() + "/static/images/upload/");
ret.put("filename", filename);
return ret;
}
