JQuery File Upload实现跨域上传

1,716 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文已参与「掘力星计划」,赢取创作大礼包,挑战创作激励金。

最近在做一个互联网项目,方案为前后端分离,主要负责前端框架设计,经过业务分析,项目采用了Requirejs+avalonjs+jquery三个框架完成开发。

前后端通过跨域实现接口调用,中间也发现和遇到了不少问题,尤其是在富文本编辑器和上传插件跨域的处理过程中,费劲了脑汁,最终总算把问题解决了,记录一下解决过程,以供大家参考和学习。

上传插件(jQuery File Upload)

上传选择了jQuery File Upload插件,兼容性还是相对不错,并且支持跨域,但是没有一个完整的跨域Demo,只能看源码找帮助,自己动手去实现。

下载地址:github.com/blueimp/jQu…

实现方法

页面引入

<link rel="stylesheet" type="text/css" href="../../src/widget/jQueryFileUpload/css/jquery.fileupload.css">
<link rel="stylesheet" type="text/css" href="../../src/widget/jQueryFileUpload/css/jquery.fileupload-ui.css">
<script type="text/javascript" src=".../../src/widget/jQueryFileUpload/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src=".../../src/widget/jQueryFileUpload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src=".../../src/widget/jQueryFileUpload/js/jquery.fileupload.js"></script>   
<!--上传页面按钮 -->
<input id="fileupload" type="file" name="files" multiple>

JS脚本

$('#fileupload').fileupload({
    url: config.getUrl()+"upload!upload.do",
    type:"POST",
    dataType:"json",
    autoUpload : true,
    acceptFileTypes: /(.|/)(jpe?g|png)$/i,
    formData: {model:1},
    forceIframeTransport: true,
    redirectParamName:"callUrl",
    redirect:"http://"+window.location.host+"/app/callupload.html?",//回调页面
    done: function (e, data) {
        $.each(data.result.files, function (index, file) {
            model.fileVO.push({attach_root_id:file.id,file_path:file.url});
        });
    },
    fail:function(e,data){
        console.log("上传失败:"+data.errorThrown);
    }
});

创建回调页面(callupload.html)

<body>
    <script type="text/javascript">
        document.body.innerText=document.body.textContent=decodeURIComponent(window.location.search.slice(1));
    </script>
</body>

后台上传API

后台使用.NET的MVC模式开发的简单的上传示例接口

string result = file.FileName;
context.Response.Headers.Add("Cache-Control", "no-cache");
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Headers", "x-requested-with");
context.Response.AddHeader("Location", callUrl + "?msg=" + result);
context.Response.Redirect(callUrl + "?msg=" + result); 

文章内容如果写的存在问题欢迎留言指出,让我们共同交流,共同探讨,共同进步~~~

文章如果对你有帮助,动动你的小手点个赞,鼓励一下,给我前行的动力。

「欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边,抽奖详情见活动文章」