springmvc+ajaxfileupload实现头像上传并预览

2024-03-12 16:38

本文主要是介绍springmvc+ajaxfileupload实现头像上传并预览,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


实现原理:利用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+")");//解析返回的jsonvar 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<String, Object> resMap = new HashMap<String, Object>();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");//指定响应内容类型,避免<pre...try {PrintWriter out = response.getWriter();Gson gson = new GsonBuilder().create();String gsonStr = gson.toJson(resMap);out.write(gsonStr);out.flush();} catch (IOException e) {e.printStackTrace();}}}



springmvc文件配置:

<!-- 文件上传相关start tanfei 2013-09-20--><!-- SpringMVC上传文件时,需要配置MultipartResolver处理器  --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --><property name="maxUploadSize" value="200000"/> </bean> <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --><bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 --><prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop> <prop key="java.lang.Exception">error_all</prop></props> </property></bean><!-- 文件上传相关end -->




jquery插件ajaxfileupload.js:

jQuery.extend({createUploadIframe: function(id, uri){//create framevar frameId = 'jUploadFrame' + id;var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';if(window.ActiveXObject){if(typeof uri== 'boolean'){iframeHtml += ' src="' + 'javascript:false' + '"';}else if(typeof uri== 'string'){iframeHtml += ' src="' + uri + '"';}	}iframeHtml += ' />';jQuery(iframeHtml).appendTo(document.body);return jQuery('#' + frameId).get(0);			},createUploadForm: function(id, fileElementId,data){//create form	var formId = 'jUploadForm' + id;var fileId = 'jUploadFile' + id;var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	var oldElement = jQuery('#' + fileElementId);var newElement = jQuery(oldElement).clone();jQuery(oldElement).attr('id', fileId);jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);/*****    增加参数的支持   *****/ if (data) {  for (var i in data) {  $('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);  }  }//set attributesjQuery(form).css('position', 'absolute');jQuery(form).css('top', '-1200px');jQuery(form).css('left', '-1200px');jQuery(form).appendTo('body');		return form;},ajaxFileUpload: function(s) {// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		s = jQuery.extend({}, jQuery.ajaxSettings, s);var id = new Date().getTime();// ADD  s.datavar form = jQuery.createUploadForm(id, s.fileElementId, s.data);var io = jQuery.createUploadIframe(id, s.secureuri);var frameId = 'jUploadFrame' + id;var formId = 'jUploadForm' + id;		// Watch for a new set of requestsif ( s.global && ! jQuery.active++ ){jQuery.event.trigger( "ajaxStart" );}            var requestDone = false;// Create the request objectvar xml = {}   if ( s.global )jQuery.event.trigger("ajaxSend", [xml, s]);// Wait for a response to come backvar uploadCallback = function(isTimeout){			var io = document.getElementById(frameId);try {				if(io.contentWindow){xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}else if(io.contentDocument){xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;}						}catch(e){jQuery.handleError(s, xml, null, e);}if ( xml || isTimeout == "timeout") {				requestDone = true;var status;try {status = isTimeout != "timeout" ? "success" : "error";// Make sure that the request was successful or notmodifiedif ( status != "error" ){// process the data (runs the xml through httpData regardless of callback)var data = jQuery.uploadHttpData( xml, s.dataType );// If a local callback was specified, fire it and pass it the dataif ( s.success )s.success( data, status );// Fire the global callbackif( s.global )jQuery.event.trigger( "ajaxSuccess", [xml, s] );} elsejQuery.handleError(s, xml, status);} catch(e) {status = "error";jQuery.handleError(s, xml, status, e);}// The request was completedif( s.global )jQuery.event.trigger( "ajaxComplete", [xml, s] );// Handle the global AJAX counterif ( s.global && ! --jQuery.active )jQuery.event.trigger( "ajaxStop" );// Process resultif ( s.complete )s.complete(xml, status);jQuery(io).unbind()setTimeout(function(){	try {jQuery(io).remove();jQuery(form).remove();	} catch(e) {jQuery.handleError(s, xml, null, e);}									}, 100)xml = null}}// Timeout checkerif ( s.timeout > 0 ) {setTimeout(function(){// Check to see if the request is still happeningif( !requestDone ) uploadCallback( "timeout" );}, s.timeout);}try {var form = jQuery('#' + formId);jQuery(form).attr('action', s.url);jQuery(form).attr('method', 'POST');jQuery(form).attr('target', frameId);if(form.encoding){jQuery(form).attr('encoding', 'multipart/form-data');      			}else{	jQuery(form).attr('enctype', 'multipart/form-data');			}			jQuery(form).submit();} catch(e) {			jQuery.handleError(s, xml, null, e);}jQuery('#' + frameId).load(uploadCallback	);return {abort: function () {}};	},/** handleError 方法在jquery1.4.2之后移除了,此处重写改方法 **/handleError: function( s, xhr, status, e ) {// If a local callback was specified, fire itif ( s.error ) {s.error.call( s.context || s, xhr, status, e );}// Fire the global callbackif ( s.global ) {(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );}},uploadHttpData: function( r, type ) {//alert("-->" + r.responseText);try{//debugger;var data = !type;data = type == "xml" || data ? r.responseXML : r.responseText;// If the type is "script", eval it in global contextif ( type == "script" ){jQuery.globalEval( data );}// Get the JavaScript object, if JSON is used.if ( type == "json" ){/*** 如果返回的是字符串(JSON格式字符串),下面会报错,导致无法走入sucess方法 加上\"  ***/// eval( "data = " + data );eval("data = \" "+data+" \" ");}// evaluate scripts within htmlif ( type == "html" ){jQuery("<div>").html(data).evalScripts();}}catch(e) {}    return data;}})



这篇关于springmvc+ajaxfileupload实现头像上传并预览的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/801888

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三