当前位置:首页 > JSP教程 > JSP常见问题

JSP使用ajaxFileUpload.js实现跨域问题

废话不多说了,直接给大家贴代码了。

jsp代码如下

$.ajaxfileupload ( { url:'http://lh.abc.com:8080/gap/gap/fileupload.do',//用于文件上传的服务器端请求地址(本机为fxb.abc.com) secureuri:false,//一般设置为false fileelementid:'file',//文件上传空间的id属性 <input type="file" id="file" name="file" /> datatype: 'jsonp',//返回值类型 一般设置为json jsonp: 'jsoncallback', jsonpcallback:'success_jsonpcallback', function success_jsonpcallback(data) { alert("1"); }, success: function (data, status) //服务器成功响应处理函数 { alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量 if(typeof(data.error) != 'undefined') { if(data.error != '') { alert(data.error); }else { alert(data.message); } } }, error: function (data, status, e)//服务器响应失败处理函数 { alert(status); alert(e); } } )

配置文件

<action name="fileupload" class="com.gap.action.fileuploadaction" method="fileupload"> <result type="json" name="success"> <param name="contenttype"> text/html </param> </result> <result type="json" name="error"> <param name="contenttype"> text/html </param> </result> </action>

action中的处理如下

public string fileupload() throws exception { string path = servletactioncontext.getrequest().getrealpath("/upload1"); // string path = configdatainfo.getconfigvalue("imgserver"); try { file f = this.getfile(); if (this.getfilefilename().endswith(".exe")) { message = "对不起,你上传的文件格式不允许!!!"; } else { fileinputstream inputstream = new fileinputstream(f); fileoutputstream outputstream = new fileoutputstream(path + "/" + this.getfilefilename()); byte[] buf = new byte[1024]; int length = 0; while ((length = inputstream.read(buf)) != -1) { outputstream.write(buf, 0, length); } inputstream.close(); outputstream.flush(); message = "上传成功"; } } catch (exception e) { e.printstacktrace(); message = "对不起,文件上传失败了!!!!"; } return success; }

每次跨域上传图片时,可以成功上传到服务器上,但是不能正确的返回信息,总是进入error方法中,正确应该进入success方法



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐