双核浏览器下在chrome内核使用uploadify总有302问题,也不知道如何修复,之所以喜欢360浏览器是因为帮客户控制渲染内核

页面默认用极速核,增加标签:<meta name="renderer" content="webkit"/> 
 若页面默认ie兼容内核,增加标签:<meta name="renderer" content="ie-comp"/> 
 若页面默认ie标准内核,增加标签:<meta name="renderer" content="ie-stand"/>

 要解决302问题也很简单就是html5的文件上传,正好最近在ueditor看到百度webuploader,会自动选择flash html5,就是一个成熟的解决方案了。

先看前端我们将最常用的操作封装插件asp.net中和MVC中最好使用相对应用程序绝对路径,自行定义全局applicationPathvar applicationPath = “@(Href(“~”)==”/”?””:Href(“~”))”; 

前端插件代码

(function ($, window) {
    var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../..";
    function S4() {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    function initWebUpload(item, options) {

        if (!WebUploader.Uploader.support()) {
            var error = "上传控件支持您的浏览器!请尝试升级flash版本或者使用Chrome引擎的浏览器。<a target='_blank' href='http://se.360.cn'>下载页面</a>";
            if (window.console) {
                window.console.log(error);
            }
            $(item).text(error);
            return;
        }

        var defaults = {
            hiddenInputId: "uploadifyHiddenInputId", // input hidden id
            onAllComplete: function (event) { }, // 当所有file上传执行回调函数
            onComplete: function (event) { },// 每上传一个file回调函数
            innerOptions: {},
            fileNumLimit: undefined,
            fileSizeLimit: undefined,
            fileSingleSizeLimit: undefined,
            PostbackHold: false
        };

        var opts = $.extend({}, defaults, options);
        var hdFileData = $("#" + opts.hiddenInputId);

        var target = $(item);//容器
        var pickerid = "";
        if (typeof guidGenerator36 != 'undefined')//给一个唯一ID
            pickerid = guidGenerator36();
        else
            pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);

        var uploaderStrdiv = '<div class="webuploader">' +
            '<div id="thelist" class="uploader-list"></div>' +
            '<div class="btns">' +
            '<div id="' + pickerid + '">选择文件</div>' +
            //'<a id="ctlBtn" class="btn btn-default">开始上传</a>' +
            '</div>' +
        '</div>';
        target.append(uploaderStrdiv);

        var $list = target.find('#thelist'),
             $btn = target.find('#ctlBtn'),//这个留着,以便随时切换是否手动上传
             state = 'pending',
             uploader;

        var jsonData = {
            fileList: []
        };

        var webuploaderoptions = $.extend({

            // swf文件路径
            swf: applicationPath + '/Scripts/lib/webuploader/Uploader.swf',

            // 文件接收服务端server: applicationPath + '/MvcPages/WebUploader/Process',

            // 选择文件的按钮。可选。
            // 内部根据当前运行创建可能input元素,也可能flash.
            pick: '#' + pickerid,

            // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
            resize: false,
            fileNumLimit: opts.fileNumLimit,
            fileSizeLimit: opts.fileSizeLimit,
            fileSingleSizeLimit: opts.fileSingleSizeLimit
        },
        opts.innerOptions);
        var uploader = WebUploader.create(webuploaderoptions);

      //回发时还原hiddenfiled的保持数据
      var fileDataStr = hdFileData.val();
      if (fileDataStr &amp;&amp; opts.PostbackHold) {
        jsonData = JSON.parse(fileDataStr);
      $.each(jsonData.fileList, function (index, fileData) {
      var newid = S4();
      fileData.queueId = newid;
      $list.append('<div id="' + newid + '" class="item">' +
        '<div class="info">' + fileData.name + '</div>' +
        '<div class="state">已上传</div>' +
        '<div class="del"></div>' +
        '</div>');
      });
      hdFileData.val(JSON.stringify(jsonData));
      }




        uploader.on('fileQueued', function (file) {//队列事件
            $list.append('<div id="' + file.id + '" class="item">' +
                '<div class="info">' + file.name + '</div>' +
                '<div class="state">等待上传...</div>' +
                '<div class="del"></div>' +
            '</div>');
        });
        uploader.on('uploadProgress', function (file, percentage) {//进度条事件
            var $li = target.find('#' + file.id),
                $percent = $li.find('.progress .bar');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<span class="progress">' +
                    '<span  class="percentage"><span class="text"></span>' +
                  '<span class="bar" role="progressbar" style="width: 0%">' +
                  '</span></span>' +
                '</span>').appendTo($li).find('.bar');
            }

            $li.find('div.state').text('上传中');
            $li.find(".text").text(Math.round(percentage * 100) + '%');
            $percent.css('width', percentage * 100 + '%');
        });
        uploader.on('uploadSuccess', function (file, response) {//上传成功事件
            target.find('#' + file.id).find('div.state').text('已上传');
            var fileEvent = {
                queueId: file.id,
                name: file.name,
                size: file.size,
                type: file.type,
                filePath: response.filePath
            };
            jsonData.fileList.push(fileEvent)
            opts.onComplete(fileEvent);

        });

        uploader.on('uploadError', function (file) {
            target.find('#' + file.id).find('div.state').text('上传出错');
        });

        uploader.on('uploadComplete', function (file) {//全部完成事件
            target.find('#' + file.id).find('.progress').fadeOut();
            var fp = $("#" + opts.hiddenInputId);
            fp.val(JSON.stringify(jsonData));
            opts.onAllComplete(jsonData.fileList);
        });

        uploader.on('fileQueued', function (file) {
            uploader.upload();
        });

        uploader.on('filesQueued', function (file) {
            uploader.upload();
        });

        uploader.on('all', function (type) {
            if (type === 'startUpload') {
                state = 'uploading';
            } else if (type === 'stopUpload') {
                state = 'paused';
            } else if (type === 'uploadFinished') {
                state = 'done';
            }

            if (state === 'uploading') {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });

        $btn.on('click', function () {
            if (state === 'uploading') {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });
        //删除
        $list.on("click", ".del", function () {
            var $ele = $(this);
            var id = $ele.parent().attr("id");
            var deletefile = {};
            $.each(jsonData.fileList, function (index, item) {
                if (item &amp;&amp; item.queueId === id) {              uploader.removeFile(uploader.getFile(id));//不要遗漏
                    deletefile = jsonData.fileList.splice(index, 1)[0];
                    $("#" + opts.hiddenInputId).val(JSON.stringify(jsonData));
                    $.post(applicationi + "/Webploader/Delete", {  'filepathname': deletefile.filePath }, function (returndata) {
                        $ele.parent().remove();
                    });
                    return;
                }
            });
        });

    }


    $.fn.powerWebUpload = function (options) {
        var ele = this;
        if (typeof PowerJs != 'undefined') {
            $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.css", function () { }, 'css');
            $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.min.js", function () {
                initWebUpload(ele, options);
            });
        }
        else {
            initWebUpload(ele, options);
        }
    }
})(jQuery, window);

页面引入上述js后使用:

$("#uploader").powerWebUpload({ hiddenInputId: "uploadhidden" }); 

html需要一个容器hidden

<div id="uploader"></div>
<asp:HiddenField ID="hfFilePath" ClientIDMode="Static" runat="server" />

MVC版后端文件接收,即便你是asp.net 引入mvcajax也是可以的:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
public class WebUploaderController : BaseController
    {
        public ActionResult Process(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            string filePathName = string.Empty;string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload\Document");
            if (Request.Files.Count == 0)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
            }
            try
            {
                filePathName = //自己这里处理文件保存返回需要保存hidden的数据,文件在file或者Request.Files[0]
            }
            catch (Exception)
            {
                return Json(new { jsonrpc = 2.0, error = new { code = 103, message = "保存失败" }, id = "id" });
            }

            return Json(new
            {
                jsonrpc = "2.0",
                id = "id",
                filePath = urlPath + "/" + filePathName
            });
        }
     static string urlPath = "../../Upload/Document";

 
        public ActionResult Delete(string filePathName)
        {
            if (string.IsNullOrEmpty(filePathName))
            {
                return Content("no");
            }
            //为了安全 检查一下路径 不够严谨 自行更具业务做更加细致的判断
            if (!filePathName.StartsWith(urlPath) ||
                filePathName.Substring(6, filePathName.Length - 7).Contains("../"))
            {
                return Content("no!");
            }
            string localFilePathName = this.Server.MapPath(filePathName);
 
            try
            {
                bool b = UploadifyManager.DeleteAttachment(localFilePathName);
                if (!b) throw new Exception("删除文件失败");
 
                return Content("ok");
            }
            catch
            {
                return Content("no");
            }
        }
    }

 —-

一开始发首页被退下来了,现在重新编辑使内容更加完整优化插件代码

 完整demohttp://yunpan.cn/cgifFwGhbGSvi  提取码 f7c1

                https://github.com/gxrsprite/AspnetMvcWebuploaderDemo

补充:

扩展自定义参数利用uploadBeforeSend事件可以扩展参数插件内可根据需要修改

cookie的问题,我用微软自带登录系统,不需要做任何特殊处理完全没有问题。

原文地址:https://blog.csdn.net/lmrylll/article/details/131208906

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_39548.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注