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

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2