首先在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("/upload"); 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; } }
时间: 2024-12-28 20:39:21