首页 > 代码库 > springMVC上传图片,使用jquery预览
springMVC上传图片,使用jquery预览
首先在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="http://www.mamicode.com/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="http://www.mamicode.com/‘+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; }}
springMVC上传图片,使用jquery预览
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。