博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springmvc+ajaxfileupload实现头像上传并预览
阅读量:4180 次
发布时间:2019-05-26

本文共 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){	 //图片文件上传	    		Map
resMap = 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文件配置:

error_fileupload
error_all

jquery插件ajaxfileupload.js:

jQuery.extend({	    createUploadIframe: function(id, uri)	{			//create frame            var frameId = 'jUploadFrame' + id;            var iframeHtml = '

转载地址:http://atqai.baihongyu.com/

你可能感兴趣的文章
CMake 手册详解(七)
查看>>
CMake 手册详解(八)
查看>>
CMake手册详解 (九)
查看>>
CMake手册详解 (十)
查看>>
CMake手册详解 (十一)
查看>>
CMake手册详解 (十二)
查看>>
CMake手册详解 (十三)
查看>>
CMake手册详解 (十四)
查看>>
CMake手册详解 (十五)
查看>>
map::lower_bound/upper_bound的使用
查看>>
C++ STL中Map的按Key排序和按Value排序
查看>>
互斥量、条件变量与pthread_cond_wait()函数的使用,详解
查看>>
IO模式设置网络编程常见问题总结
查看>>
windows 编译webrtc 58版本库
查看>>
git tag操作教程
查看>>
Ubuntu系统中git每次提交都要输入密码怎么办?
查看>>
constexpr关键字
查看>>
std::copy详解
查看>>
C++11 新特性摘抄
查看>>
WebRTC学习之函数的异步执行
查看>>