c# 跨域上传 jQueryFileUpload 的另类用法

普通的文件上传好实现, 跨域文件上传就不好办了.
首先声明, 我的这个用法不是官方提供的方式. 是我自己写的. 简单好理解.

jQueryFileUpload 的跨域上传有2种方式,具体怎么上传, 官方的说明是:https://github.com/blueimp/jQuery-File-Upload/wiki/Cross-domain-uploads

无奈这种纯英文的文档不是很好看懂.

哎, 本人比较懒. 就不写说明了, 贴代码吧.

为了代码不泄漏, 我把安全验证的代码去掉了, 使用者请自行添加安全验证相关代码.

说下大体流程.
1.为了好看上传界面的html代码,隐藏了file, 用一个label 按钮激活file界面,
这一步我用的是JqueryFileUpload, 其实自己手写一个 iframe 隐藏掉, 效果是一样的. 但是我这个界面还有form, 里面的元素还挺多, 就将就着用了jQueryFileUpload ,免去再写个form 了.

2.jQueryFileUpload 将文件上传到文件服务器上UploadFile.ashx
3.UploadFile.ashx会带着成功的参数跳转到redirect 指定的页面CrossSiteFileUploadSuccess.cshtml 实现参数接收和跨域.
4.CrossSiteFileUploadSuccess.cshtml 页面接收到参数 之后,在iframe中调用父页面的OnFileUploaded函数.把参数传给父页面.

 <div class="form-group col-md-6 col-lg-6">
   <label for="BusinessLicenseFileUpload">营业执照:</label>
   @{YZ.Bind("BusinessLicense").MaxLength(200).ToString();}
   <!-- 此盒子与插件功能无关 显示上传图片的预览 未上传时时默认图 一般为灰色底图  -->
   <div class="img_box">
       <a v-bind:href="editData.BusinessLicense" target="_blank">
           <img v-bind:src="editData.BusinessLicense" alt="营业执照" width="200" height="100" />
       </a>
   </div>
   <label class="btn btn-default" type="button" for="BusinessLicenseFileUpload">上传营业执照</label>
   <input type="hidden" class="form-control" id="BusinessLicense" name="BusinessLicense" v-model="editData.BusinessLicense" />
   <input class="JqueryFileUpload" id="BusinessLicenseFileUpload" type="file" name="fileName" style="display:none;" />
   <span for="BusinessLicense" class="field-validation-error"></span> 
</div>

<script>
    var FileStoreServer =  '@ViewBag.FileStoreServer';
    //当文件上传成功后,会调用这个方法
    function OnFileUploaded(DocumentElementId, FilePath, Message)
    {
        //alert("OnFileUploaded");
        //debugger;
        var httpurl = FileStoreServer +'/HttpFileServer/GetFile.ashx?key=' + FilePath;
        if (Message == "上传成功")
        {
            //$('.img_box img').attr('src', httpurl);//动态修改预览图的src 
            //$("#" + DocumentElementId).val(httpurl);//图片上传成功后 后台返回来的图片路径  前后台要约定好 
            if (DocumentElementId == "BusinessLicense")
            {
                editVueData.BusinessLicense = httpurl;
            }
            else if (DocumentElementId == "LicensingPractice")
            {
                editVueData.LicensingPractice = httpurl;
            }
            
        } else {
            alert(Message);
        }
    }

    /*3.2 初始化 上传图片*/
    //console.log($('#fileUpload').fileupload);
    setTimeout(function () {

        //关于跨站文件上传,需要参考文档. https://github.com/blueimp/jQuery-File-Upload/wiki/Cross-domain-uploads
        $('#BusinessLicenseFileUpload').fileupload({
            url: FileStoreServer +'/HttpFileServer/UploadFile.ashx',
            dataType: 'json',
            autoUpload: true,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|xlsx)$/i,//允许上传的的文件类型
            maxFileSize: 999000,//(999KB), //单位:B         
            forceIframeTransport: true,//用Iframe实现跨域文件上传,成功后会调用OnFileUploaded
            add: function (e, data) { 
                data.submit();
            } 
        });
         
        //文件上传前触发事件
        $('#BusinessLicenseFileUpload').bind('fileuploadsubmit', function (e, data) {
            data.formData = {//如果需要额外添加参数可以在这里添加
                FilePath: "/BusinessLicenseFiles/" + $("#CustomerID").val() + ".bmp",
                DocumentElementId: "BusinessLicense",//此组件被赋值
                redirect: window.location.href.replace(/\/[^/]*$/, '/BaseInfo/CustomerInfo/CrossSiteFileUploadSuccess?DocumentElementId={DocumentElementId}&FilePath={FilePath}&Message={Message}'),
            };
        });
    }, 800);
 

</script>

CrossSiteFileUploadSuccess.cshtml 的源代码, 这个文件是跟上面的html代码放在同一个项目里的, 这个页面就是负责接收参数的, 可以跨域接收参数.

<script>
    debugger
    window.parent.OnFileUploaded('@Request["DocumentElementId"]', '@Request["FilePath"]', '@Request["Message"]')
</script>

文件存储服务器上 HttpFileServer/UploadFile.ashx 的源代码,

using System;
using System.Collections.Generic; 
using System.Web;

namespace WebService
{
    /// <summary>
    /// 上传PDF报告单, 到这个处理程序, 会进行保存.
    /// </summary>
    public class UploadFile  : IHttpHandler
    {
        static string FlieSaveRootDir; 
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                var fliename = context.Request["FilePath"];
                if (string.IsNullOrEmpty(fliename))
                {
                    context.Response.Write("必须指定参数 FilePath");
                    //context.Response.End();
                    return;
                }

                if (FlieSaveRootDir == null)
                {
                    FlieSaveRootDir = System.IO.File.ReadAllText(context.Server.MapPath("~/RootPath.config"));
                }
                var path = string.Format("{0}\\{1}", FlieSaveRootDir, fliename);

                var dir = System.IO.Path.GetDirectoryName(path);
                if (!System.IO.Directory.Exists(dir))
                {
                    System.IO.Directory.CreateDirectory(dir);
                }

                context.Request.Files[0].SaveAs(path);
                context.Response.ContentType = "text/plain";

                //byte[] bt = System.Text.Encoding.Default.GetBytes(fliename);

                //context.Response.Write("SUCCESS:" + Convert.ToBase64String(bt));

               
                var redirect = context.Request["redirect"]; 
               
                if (!string.IsNullOrEmpty(redirect))
                {
                    var Message = "上传成功";
                    //var referer = context.Request.Headers["referer"];//取得来源地址
                    //context.Response.Write("<script>document.domain = '*';</script>");
                    context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                    context.Response.Headers["Access-Control-Allow-Credentials"] = "true";
                    context.Response.Headers["Access-Control-Allow-Methods"] = "OPTIONS, HEAD, GET, POST, DELETE";
                    context.Response.Headers["Access-Control-Allow-Headers"] ="Content-Type, Content-Range, Content-Disposition";
                    var DocumentElementId = context.Request["DocumentElementId"];
                    redirect = redirect.Replace("{DocumentElementId}", DocumentElementId);
                    redirect = redirect.Replace("{FilePath}", System.Web.HttpUtility.UrlEncode(fliename));
                    redirect = redirect.Replace("{Message}", System.Web.HttpUtility.UrlEncode(Message));
                    context.Response.ContentType = "text/html";//必须是这个,否则不运行下面的代码
                    context.Response.Write("<script>debugger; window.location.href = '" + redirect + "';</script>");
                    /* 在redirect 的目的页面中
                     * <script> 
                        window.parent.OnFileUploaded('@Request["DocumentElementId"]', '@Request["FilePath"]', '@Request["Message"]')
                       </script>
                     */
                    /* 在 原提交文件的页面中 增加
                       <script> //当文件上传成功后,会调用这个方法
                        function OnFileUploaded(DocumentElementId, FilePath, Message)
                        { 
                            var httpurl = '//localhost:8000/HttpFileServer/GetFile.ashx?key=' + FilePath;
                            if (Message == "上传成功")
                            {
                                //$('.img_box img').attr('src', httpurl);//动态修改预览图的src 
                                //$("#" + DocumentElementId).val(httpurl);//图片上传成功后 后台返回来的图片路径  前后台要约定好  
                            } else {
                                alert(Message);
                            }
                        }
                        </script>
                     */

                }
                else {
                    context.Response.Write("SUCCESS:" + System.Web.HttpUtility.UrlEncode(fliename));
                }
                //context.Response.End();
            }
            catch(Exception ex)
            {
                context.Response.Write("FAIL:" + ex.Message);
                //context.Response.End(); 
            }
        }


         
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值