本文共 9267 字,大约阅读时间需要 30 分钟。
实现原理:利用ajaxfileupload.js + springmvc进行图片文件的上传,再利用base64编码技术得到图片的编码字符串,并返回到页面进行img预览。还可以吧编码字符串存入数据库,较大文件不建议存入数据库。(需要jquery支持)
js代码:
/** * 图片上传 */function ajaxFileUpload() { $.ajaxFileUpload({ url:'../../../hr/upload.do', //需要链接到服务器地址 secureuri:false, fileElementId:'file', //文件选择框的id属性 dataType: 'json', //服务器返回的格式类型 success: function (data, status) //成功 { var json = eval("("+data+")");//解析返回的json var imageCode = json.imageCode; if(imageCode!='-1'){ $("#showImg").attr("src", imageCode); $("#input_photo").val(imageCode); }else{ alert("上传失败!只允许上传图片类型(jpg,gif,png)且小于1M的照片"); } }, error: function (data, status, e) //异常 { alert("出错了,请重新上传!"); } });}
java代码:
import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.commons.CommonsMultipartFile;import com.cpeam.hr.util.ImageUtil;import com.google.gson.Gson;import com.google.gson.GsonBuilder;/** * 图片上传控制器 * @author tanfei * @date 2013-09-23 */@Controller@RequestMapping("/hr")public class ImgUploadAction { @RequestMapping(value="uploadImg") public void uploadImg() { } /** * 上传 * @param file * @param request * @param model * @return */ @RequestMapping(value="/upload",method=RequestMethod.POST) public void fileUpload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request ,HttpServletResponse response){ //图片文件上传 MapresMap = new HashMap (); String imageCode = "-1";//默认上传失败 /**判断文件是否为空,空直接返回上传错误**/ if(!file.isEmpty()){ //获得文件后缀名 String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); if(suffix.equals(".jpg") || suffix.equals(".gif") || suffix.equals(".png")) {//检测图片类型 if(file.getSize() > 1000000) { imageCode = "-1"; //throw new Exception("上传失败:文件大小不能超过1M"); }else { try { //将上传的图片转换成base64编码字符串 imageCode = "data:image/gif;base64," + ImageUtil.encodeImageToStr(file.getInputStream()); } catch (IOException e) { e.printStackTrace(); } } } }else{ imageCode = "-1"; } resMap.put("imageCode", imageCode); response.setContentType("text/html;charset=UTF-8");//指定响应内容类型,避免
springmvc文件配置:
jquery插件ajaxfileupload.js:error_fileupload error_all
jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; var iframeHtml = '
转载地址:http://atqai.baihongyu.com/