Ⅰ springMVC jsp页面使用ajax方式将数据(上传图片对应的数据流)传递到controller中处理
客户端将图片转为BASE64,以字符串传到后端,再转成字节流保存。
Ⅱ ajaxfileupload+springmvc上传多文件的control怎么写
1.Spring mvc a.xml配置:[html] view plain print?<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!– set the max upload size1MB 1048576 –> <property name="maxUploadSize"> <value>52428800</value> </property> <property name="maxInMemorySize"> <value>2048</value> </property> </bean> b. 服务器端接收解析[java] view plain print? public void imgUpload( MultipartHttpServletRequest multipartRequest, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=UTF-8"); Map<String, Object> result = new HashMap<String, Object>(); //获取多个file for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) { String key = (String) it.next(); MultipartFile imgFile = multipartRequest.getFile(key); if (imgFile.getOriginalFilename().length() > 0) { String fileName = imgFile.getOriginalFilename(); //改成自己的对象哦! Object obj = new Object(); //Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径 try { String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_GOODIMG_URL); File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName); if (_apkFile.exists()) { FileInputStream fis = new FileInputStream(_apkFile); } else throw new FileNotFoundException("apk write failed:" + fileName); List list = new ArrayList(); //将obj文件对象添加到list list.add(obj); result.put("success", true); } catch (Exception e) { result.put("success", false); e.printStackTrace(); } } } String json = new Gson().toJson(result, new TypeToken<Map<String, Object>>() { }.getType()); response.getWriter().print(json); } //保存文件 private File saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException { File file = new File(path + "/" + filename); FileOutputStream fs = new FileOutputStream(file); byte[] buffer = new byte[1024 * 1024]; int bytesum = 0; int byteread = 0; while ((byteread = stream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); fs.flush(); } fs.close(); stream.close(); return file; } 2.关于前端代码a.修改ajaxfileupload.js 先到官网下载该插件. 将源文件的createUploadForm的代码替换如下:[javascript] view plain print?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>'); if (data) { for ( var i in data) { jQuery( '<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); } } for (var i = 0; i < fileElementId.length; i ++) { var oldElement = jQuery('#' + fileElementId[i]); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileElementId[i]); jQuery(oldElement).attr('name', fileElementId[i]); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); } //set attributes jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body'); return form; } 第一步高定b. 页面代码 html:[html] view plain print?<input type="button" value="添加附件" onclick="createInput('more');" /> <div id="more"></div> js:这里可以专门写封装类,以及给file加onchange事件判断文件格式。由于时间有限,未修改[javascript] view plain print?var count = 1; /** * 生成多附件上传框 */ function createInput(parentId){ count++; var str = '<div name="div" ><font style="font-size:12px;">附件</font>'+ ' '+ '<input type="file" contentEditable="false" id="uploads' + count + '' + '" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button" value="删除" onclick="removeInput(event)" />'+'</div>'; document.getElementById(parentId).insertAdjacentHTML("beforeEnd",str); } /** * 删除多附件删除框 */ function removeInput(evt, parentId){ var el = evt.target == null ? evt.srcElement : evt.target; var div = el.parentNode; var cont = document.getElementById(parentId); if(cont.removeChild(div) == null){ return false; } return true; } 下面是2个修改多file用的js,用于显示和删除,可以于上面的合并精简代码:[javascript] view plain print?function addOldFile(data){ var str = '<div name="div' + data.name + '" ><a href="#" style="text-decoration:none;font-size:12px;color:red;" onclick="removeOldFile(event,' + data.id + ')">删除</a>'+ ' ' + data.name + '</div>'; document.getElementById('oldImg').innerHTML += str; } function removeOldFile(evt, id){ //前端隐藏域,用来确定哪些file被删除,这里需要前端有个隐藏域 $("#imgIds").val($("#imgIds").val()=="" ? id :($("#imgIds").val() + "," + id)); var el = evt.target == null ? evt.srcElement : evt.target; var div = el.parentNode; var cont = document.getElementById('oldImg'); if(cont.removeChild(div) == null){ return false; } return true; } ajax上传文件:[javascript] view plain print?function ajaxFileUploadImg(id){ //获取file的全部id var uplist = $("input[name^=uploads]"); var arrId = []; for (var i=0; i< uplist.length; i++){ if(uplist[i].value){ arrId[i] = uplist[i].id; } } $.ajaxFileUpload({ url:'xxxxx', secureuri:false, fileElementId: arrId, //这里不在是以前的id了,要写成数组的形式哦! dataType: 'json', data: { //需要传输的数据 }, success: function (data){ }, error: function(data){ } }); }
Ⅲ springmvc怎么控制文件上传的类型
spring 里面CommonsMultipartResolver通过配置上传解析器,后台代码通过一个MultipartHttpServletRequest获取上传文件,然后获取文件名称,截取后缀,那样你就可以上传你想要的文件类型,看下面画线的 .
Ⅳ springmvc怎么接受ajax发送过来的文件
你文件上传用的什么方式如果是submit直接提交的需要给form加一个属性:enctype="multipart/form-data"如果是异步提交则需要看你的上传控件的ID是否正确
Ⅳ springmvc+ajax上传图片的问题。传过去的是空值.怎么接收图片
因为SpringMVC只有GET请求才能通过方法上加参数获取到值,POST是不能通过这种方式获取的,可以通过request.getParameter(key) 或者 封装成对象(属性对应前端参数)会自动填充。另外我记得Ajax上传文件不能直接用$.ajax这种方式传,我的方法如下:var form = new FormData();var xhr = new XMLHttpRequest();xhr.open("post", "url", true);xhr.onload = function () {alert("上传完成!");};xhr.send(form);
Ⅵ 求解Spring mvc 文件上传采用jquery插件 AjaxFileUpload.js 出现的一些问题
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>checkbox</title> <script src="js/jquery-1.3.2.js" type="text/javascript"></script> <script src="js/1.js" type="text/javascript"></script> </head> <body> <table id="table1"> <tr> <td><input type="checkbox" value="1"/>1</td> <td id="k_1"><input type="text" name="student" id="s_1" readonly="true"/></td> </tr> <tr> <td><input type="checkbox" value="2"/>2</td> <td id="k_2"><input type="text" name="student" id="s_2" readonly="true"/></td> </tr> <tr> <td><input type="checkbox" value="3"/>3</td> <td id="k_3"><input type="text" name="student" id="s_3" readonly="true"/></td> </tr> <tr> <td><input type="checkbox" value="4"/>4</td> <td id="k_4"><input type="text" name="student" id="s_4" readonly="true"/></td> </tr> </table> </body> </html> ————————————————————- $(document).ready(function() { $("td[id^='k_']").hide(); var check = $(":checkbox"); //得到所有被选中的checkbox var actor_config; //定义变量 check.each(function(i){ actor_config = $(this); actor_config.click( function(){ if($(this).attr("checked")==true){ $("#k_"+$(this).val()).show(); }else{ $("#k_"+$(this).val()).hide(); } } ); }); });
Ⅶ springmvc怎么用ajax上传
ajaxdata改成这样data:{username:username},后台方法publicvoidajaxDatas(@RequestParam(value="username",required=true)Stringusername){sysout(username);}其他不变试试
Ⅷ springmvc 多文件上传 MultipartFile 怎么获取前台传过来的参数
用@ResponseBody @RequestMapping(value = "/address", method = RequestMethod.POST) @ResponseBody public Map<String, Object> addressPOST() { Map<String, Object> map = new HashMap<>(); ReceivedGoodsAddress receivedgoodsaddress=new ReceivedGoodsAddress(); List<ReceivedGoodsAddress> list = addressService.findReceivedGoodsAddress(receivedgoodsaddress); map.clear(); map.put("list", list); return map; } //前台用jquery+ajax $.ajax({ type:'POST', url:'${contextPath}/address', dataType:'json', success:function(data){ $.each(data.list,function(i,item){ alert(i); alert(item.id); alert(item.name); }); } });
Ⅸ extjs5.0加springMVC如何实现将文件上传到本地tomcat上
用 springMVC 来做项目,如果遇到文件上传,那么一定要用 spring 自带的文件处理类来处理上传的文件,因为效率实在高过其他的。从界面传过来的参数,如果设置了值对象,那么可以从值对象里面取出字符串类型的普通参数,如果不这样做,也可以直接从 request 里面获得,两种方法都可以。问题是如果值对象里面写了其他类型的变量,妄想像 Struts2 那样处理,springMVC 就会报出 400 Bad Request 的错误。在 Struts2 里面,我们可以定义一个值对象为public class ImageVo { private String roomnumber; private File image1 ; private File image2 ;private File image3 ;}然后在后台从前台传过来的值对象里面取出image1……,那就是一个文件流了,非常好处理上传文件。但 springMVC 只能接受全部为 string 类型的字符串值,那么该怎么做呢?前台Extjs4代码:/** * 图片添加 * @type {Ext.form.Panel} */var addImageForm = new Ext.form.Panel({ border: false, bodyPadding: 5, id: 'addImageForm',height:350, fieldDefaults: {labelWidth: 80, labelSeparator: ": ", anchor: '95%'}, items: [ {xtype:'fieldset',title:'图片上传', collapsible:true, items:[ { xtype:'textfield', fieldLabel: '房间号码', name: 'roomnumber', id: 'roomnumber1', allowBlank: false, maskRe: /[\d]/, reegx: /[\d{4}]/, minLength: 4, maxLength: 4, emptyText: '请输入四位的房间号码(前两位代表楼层,后两位代表房间号)', regexText: '请输入正确的房间号码', //验证该房间号码是否存在 ! listeners: { blur: function (e, t, eOpts) { var roomnumber = e.rawValue; if(roomnumber.length == 4){ Ext.Ajax.request({ method: 'post', params: {roomnumber: roomnumber}, url: '/room/findroomhold', callback: function (options, success, response) { var jsonString = Ext.JSON.decode(response.responseText); if (jsonString.success) { } else { Ext.Msg.alert('警告', jsonString.msg); } } }); } } } },{ xtype:'filefield', fieldLabel:'上传图片1', name:'image1', id:'image1', buttonText:'', buttonConfig:{iconCls:'upload'}, listeners:{ change:function(btn, value, eOpts){ var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/; if ( img_reg.test(value) ) { var img = Ext.getCmp('img1'); var file = btn.fileInputEl.dom.files[0]; var url = URL.createObjectURL(file); img.setSrc(url); } else { Ext.Msg.alert('提示', '请选择图片类型的文件!'); return ; } } } },{ xtype:'filefield', fieldLabel:'上传图片2', name:'image2', id:'image2', buttonText:'', buttonConfig:{iconCls:'upload'}, listeners:{ change:function(btn, value){ var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/; if ( img_reg.test(value) ) { var img = Ext.getCmp('img2'); var file = btn.fileInputEl.dom.files[0]; var url = URL.createObjectURL(file); img.setSrc(url); } else { Ext.Msg.alert('提示', '请选择图片类型的文件!'); return ; } } } },{ xtype:'filefield', fieldLabel:'上传图片3', name:'image3', id:'image3', buttonText:'', buttonConfig:{iconCls:'upload'}, listeners:{ change:function(btn, value){ var img_reg = /\.([jJ][pP][gG]){1}$|\.([jJ][pP][eE][gG]){1}$|\.([gG][iI][fF]){1}$|\.([pP][nN][gG]){1}$|\.([bB][mM][pP]){1}$/; if ( img_reg.test(value) ) { var img = Ext.getCmp('img3'); var file = btn.fileInputEl.dom.files[0]; var url = URL.createObjectURL(file); img.setSrc(url); } else { Ext.Msg.alert('提示', '请选择图片类型的文件!'); return ; } } } } ] },{xtype:'fieldset',title:'图片预览',layout:'column',defaults:{width:130}, items:[ {xtype:'image',id:'img1'}, {xtype:'image',id:'img2'}, {xtype:'image',id:'img3'} ] } ], dockedItems: [ { xtype: 'toolbar', dock: 'bottom', ui: 'footer', layout: {pack: 'center'}, items: [ {text: '确认上传', disabled: true, formBind: true, handler: function () { var form = this.up('form').getForm(); if (form.isValid()) { form.submit({ url: '/image/add', method: 'post', submitEmptyText: false, waitMsg: '请稍等,系统正在帮您添加', success: function (form, action) { //Ext.Msg.alert('成功', "上传成功!"); Ext.Msg.alert('成功', action.result.msg); }, failure: function (form, action) { Ext.Msg.alert('失败', action.result.msg); //Ext.Msg.alert('失败', "上传失败"); } }) } }}, {text: '重置', handler: function () { this.up('form').getForm().reset(); }} ] } ]});
Ⅹ spring mvc上传怎么用ajax
准备工作:前端引入:1、jquery,我在这里用的是:jquery-1.10.2.min.js 2、ajaxfileupload.js这里可能会报一些错,所以在json判断那里修改为(网上也有):Js代码 if ( type == "json" ){ data = r.responseText; var start = data.indexOf(">"); if(start != -1) { var end = data.indexOf("<", start + 1); if(end != -1) { data = data.substring(start + 1, end); } } eval( "data = " + data ); } 末尾那里补充一段:Js代码 handleError: function( s, xhr, status, e ) { if ( s.error ) { s.error.call( s.context || window, xhr, status, e ); } if ( s.global ) { (s.context ? jQuery(s.context) : jQuery.event).trigger ( "ajaxError", [xhr, s, e] ); } } 后台导入spring的jar包,我这里用的是:spring3.0.5在spring.xml里配置如下:Xml代码 <!– SpringMVC上传文件时,需要配置MultipartResolver处理器 –> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <!– 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 –> <!– 不在这里限制了,后台各自进行限制了 <property name="maxUploadSize" value="2000000"/> –> </bean> <!– SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart. –> <!– 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 –> <bean id="exceptionResolver" class="org.springframework.web.servlet.handler."> <property name="exceptionMappings"> <props> <!– 遇到异常时,跳转到/page/html/errorGolbal.html页面 –> <prop key="org.springframework.web.multipart.">/page/html/errorGolbal.html</prop> </props> </property> </bean> 这里就充分利用框架的便利性帮你都做好了,如果你不在xml里配置这些,那么在controller那里,request.getInputStream()得到的这个流不全是文件流,还包含了其他,需要你自己编码去解析,当然,要解析的话还要知道http相关报文解析知识,所以这里可以充分利用框架的便利性,有兴趣的可以研究下好了,准备工作做好了,看下前端的具体代码:Html代码 <div id="fileUpLoad" class="manage"> 添附文件 <!– 自定义 <input type="file"/> –> <input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden" /> <input type="text" id="txtFoo" readonly="readonly" style="width: 300px" /> <button onclick="btnFile.click()" style="height: 25px;">选择文件</button> </div> js代码为:Js代码 if (!window.com) { window.com = {}; } if (!window.com.company) { window.com.company= {}; } if (!window.com.company.project) { window.com.company.project= {}; } if (!window.com.company.project.services) { window.com.company.project.services = {}; } if (!window.com.company.project.services.newCase) { window.com.company.project.services.newCase = {}; } //生成随机guid数(参考网上) com.company.project.services.newCase.getGuidGenerator = function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4()); }; //上传文件 com.company.project.services.newCase.fileUpLoad = function(){ var fileName = $("#btnFile").val();//文件名 fileName = fileName.split("\\"); fileName = fileName[fileName.length-1]; var guid = com.company.project.services.newCase.getGuidGenerator();//唯一标识guid var data = {guid:guid}; jQuery.ajaxSettings.traditional = true; $.ajaxFileUpload({ url : '/PROJECT/function.do?method=fileUpLoad', secureuri : false,//安全协议 fileElementId:'btnFile',//id type : 'POST', dataType : 'json', data:data, async : false, error : function(data,status,e) { alert('Operate Failed!'); }, success : function(json) { if (json.resultFlag==false){ alert(json.resultMessage); }else{ alert('文件上传成功!'); var next = $("#fileUpLoad").html(); $("#fileUpLoad").html("<div id='"+guid+"'>"+"文件:"+fileName+" <a href='#' onclick='com.company.project.services.newCase.filedelete("+"\""+guid+"\""+","+"\""+fileName+"\""+")'>删除</a>"+"<br/></div>"); $("#fileUpLoad").append(next); } } }); }; //文件删除 com.company.project.services.newCase.filedelete = function(guid,fileName){ jQuery.ajaxSettings.traditional = true; var data = {guid:guid,fileName:fileName}; $.ajax({ url : '/PROJECT/function.do?method=filedelete', type : 'POST', dataType : 'json', data:data, async : false, error : function() { alert('Operate Failed!'); }, success : function(json) { if (json.resultFlag==false){ alert(json.resultMessage); }else{ alert('删除成功!'); $("#"+guid).remove(); } } }); }; ———————————————————————————-注:如果你对ajax不熟悉,或者由于浏览器等原因,致使上述方式提交出现各种问题,那么你可以用form表单形式提交,代码片段如下:Html代码 <div id="fileUpLoad" class="manage"> <form id="needHide" action="/工程/function.do?method=fileUpLoad" method="post" enctype="multipart/form-data" target = "hidden_frame"> <!– 自定义 <input type="file"/> –> <input type="file" id="btnFile" name="btnFile" onchange="txtFoo.value=this.value;com.company.project.services.newCase.fileUpLoad()" hidden="hidden"/> </form> 添附文件 <input type="text" id="txtFoo" readonly="readonly" style="width: 300px" /> <button onclick="btnFile.click()" style="height: 25px;">选择文件</button> <iframe name='hidden_frame' id="hidden_frame" style='display: none' onload="com.company.project.services.newCase.statusCheck()"></iframe> </div> js代码写为:Js代码 var flag = true; com.company.project.services.newCase.statusCheck = function(){ if(flag == false){ var status = hidden_frame.window.document.getElementById("hideForm").innerHTML; console.log(status); } flag = false; }; //上传文件 com.company.project.services.newCase.fileUpLoad = function(){ $("#needHide").submit(); } 后台代码主要在最后变为:Java代码 PrintWriter printWriter = response.getWriter(); printWriter.write("<div id='hideForm'>1111</div>"); ———————————————————————————-后台对应java代码段为:Java代码 @RequestMapping(params = "method=fileUpLoad") //btnFile对应页面的name属性 public void fileUpLoad(@RequestParam MultipartFile[] btnFile, HttpServletRequest request, HttpServletResponse response){ try{ //文件类型:btnFile[0].getContentType() //文件名称:btnFile[0].getName() if(btnFile[0].getSize()>Integer.MAX_VALUE){//文件长度 OutputUtil.jsonArrOutPut(response, JSONArray.fromObject("上传文件过大!")); } InputStream is = btnFile[0].getInputStream();//多文件也适用,我这里就一个文件 //String fileName = request.getParameter("fileName"); String guid = request.getParameter("guid"); byte[] b = new byte[(int)btnFile[0].getSize()]; int read = 0; int i = 0; while((read=is.read())!=-1){ b[i] = (byte) read; i++; } is.close(); OutputStream os = new FileOutputStream(new File("D://"+guid+"."+btnFile[0].getOriginalFilename()));//文件原名,如a.txt os.write(b); os.flush(); os.close(); OutputUtil.jsonOutPut(response, null); }catch (Exception e) { OutputUtil.errorOutPut(response, "系统异常"); } } @RequestMapping(params = "method=filedelete") public void filedelete(HttpServletRequest request, HttpServletResponse response){ try{ String guid = request.getParameter("guid"); String fileName = request.getParameter("fileName"); File file = new File("D://"+guid+"."+fileName); boolean isDeleted = file.delete(); if(!isDeleted){ OutputUtil.errorOutPut(response, "文件删除失败"); } OutputUtil.jsonArrOutPut(response, null); }catch (Exception e) { OutputUtil.errorOutPut(response, "系统异常"); } } 另外:如果是图片上传的话,你也可以不保存在什么临时目录,可以用base64进行编解码,网上也有很多,简单介绍下:后台只要这么做:Java代码 //得到byte数组后 BASE64Encoder base64e = new BASE64Encoder(); JSONArray ja = new JSONArray(); String base64Str = base64e.encode(b); ja.add(base64Str); OutputUtil.jsonArrOutPut(response, JSONArray.fromObject(ja)); 前台页面只要这么就可以拿到了:Html代码 $("#fileUpLoad") .append("<image src='"+"data:image/gif;base64,"+json.resultMessage[0]+"' >"); 对于json相关不大了解的可以参考我的博文:http://quarterlifeforjava.iteye.com/blog/2024336效果和iteye的相似:补充:如果要让表单提交后还是留在当前页面,除了Ajax还可以用iframe,代码如下:其实关键就是iframe和form中的target