• asp.net mvc 使用uploadfiles 实现异步上传数据


    lesg.cn

    文章发布在:  http://www.lesg.cn/netdaima/net/2017-990.html

    在实际开发过程中, 为了提高用户的体验,在上传文件的时候通常会使用异步上传文件的方式来实现;

    然而,自己实现的话界面css、js、后台代码等多个方面的工作量来看,并不是很划算; 毕竟异步上传的代码并不是核心代码;

    开发产品建议遵循一个理念,除了核心代码, 核心业务之外; 其他的代码均建议采用可靠的第三方服务;

    这里推荐一个不错的异步上传组件; “uploadfiles ”

    uploadfiles  是基于jquery 开发的一个上传组件;它已经集成了 css js ; 使用非常方便;基本上就是复制黏贴;

    lesg.cn 乐水果代码分享提供了这个组件的下载地址:

    以下是下载地址: http://lesg.cn/down/uploadfiles.zip 点击此处下载

    Demo 下载地址:

    点击此处下载demo

    下面是使用代码:

    第一步引入css 和JS文件

    <link href="../../script/uploadfiles/css/zyUpload.css" rel="stylesheet" />
     
    <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
     
    <script src="../../script/uploadfiles/js/zyUpload.js"></script>
    <script src="../../script/uploadfiles/js/zyFile.js"></script>

    第二步, 在body中创建一个 容器用于自动生成图片上传的界面

    <form id="form1">
     
    <div>
    <div id="demo" class="demo"></div>
    </div>
    </form>

    第三步,在script 创建生成项

    $(function () {
    // 初始化插件
    $("#demo").zyUpload({
     "600px", // 宽度
    height: "400px", // 宽度
    itemWidth: "140px", // 文件项的宽度
    itemHeight: "115px", // 文件项的高度
    url: "/Jewelry_UpLoad/UploadFile/@Html.Raw(ViewData["key"])", // 上传文件的路径
    fileType: ["gif", "png", "jpg", "jpeg", "bmp"],// 上传文件的类型
    fileSize: 51200000, // 上传文件的大小
    multiple: true, // 是否可以多个文件上传
    dragDrop: true, // 是否可以拖动上传文件
    tailor: true, // 是否可以裁剪图片
    del: true, // 是否可以删除文件
    finishDel: false, // 是否在上传文件完成后删除预览
    /* 外部获得的回调接口 */
    onSelect: function (selectFiles, allFiles) { // 选择文件的回调方法 selectFile:当前选中的文件 allFiles:还没上传的全部文件
    console.info("当前选择了以下文件:");
    console.info(selectFiles);
    },
    onDelete: function (file, files) { // 删除一个文件的回调方法 file:当前删除的文件 files:删除之后的文件
    console.info("当前删除了此文件:");
    console.info(file.name);
    $("input[id='" + file.name + "']").remove();
    },
    onSuccess: function (file, response) { // 文件上传成功的回调方法
    console.info("此文件上传成功:");
    console.info(file.name);
    console.info("此文件上传到服务器地址:");
    console.info(response);
    $("#uploadInf").append("<p>上传成功,文件地址是:" + response + "</p>");
     
    $(".dv_file_list").append('<input class="form-control" type="text" name="img_list" id="' + file.name + '" value="' + response + '" />');
    },
    onFailure: function (file, response) { // 文件上传失败的回调方法
    console.info("此文件上传失败:");
    console.info(file.name);
    },
    onComplete: function (response) { // 上传完成的回调方法
    console.info("文件上传完成");
    console.info(response);
    }
    });
    });

    第四步,在后台创建以下代码

    public string UploadFile()
    {
    //上传配置
    int size = 3; //文件大小限制,单位MB //文件大小限制,单位MB
    string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" }; //文件允许格式
    //上传图片
    Hashtable info = new Hashtable();
    FiUpload up = new FiUpload();
    string path = "/Content/Images/jewelry";
     
    info = up.upFile(this, path + '/', filetype, size); //获取上传状态
    return info["url"].ToString();
    }
     
    &nbsp;
     
    public class FiUpload
    {
    string state = "SUCCESS";
     
    string URL = null;
    string currentType = null;
    string uploadpath = null;
    string filename = null;
    string originalName = null;
    //HttpPostedFile uploadFile = null;
    HttpPostedFileBase uploadFile = null;
    /// <summary>
    /// 上传文件的主处理方法
    /// </summary>
    /// <param name="cxt"></param>
    /// <param name="pathbase"></param>
    /// <param name="filetype"></param>
    /// <param name="size"></param>
    /// <returns></returns>
    public Hashtable upFile(Controller cxt, string pathbase, string[] filetype, int size)
    {
    uploadpath = cxt.Server.MapPath(pathbase);//获取文件上传路径
     
    try
    {
     
    uploadFile = cxt.Request.Files[0];
    originalName = uploadFile.FileName;
     
    //目录创建
    createFolder();
     
    //格式验证
    if (checkType(filetype))
    {
    //不允许的文件类型
    state = "u4e0du5141u8bb8u7684u6587u4ef6u7c7bu578b";
    }
    //大小验证
    if (checkSize(size))
    {
    //文件大小超出网站限制
    state = "u6587u4ef6u5927u5c0fu8d85u51fau7f51u7ad9u9650u5236";
    }
    //保存图片
    if (state == "SUCCESS")
    {
    filename = NameFormater.Format(cxt.Request["fileNameFormat"], originalName);
    var testname = filename;
    var ai = 1;
    while (File.Exists(uploadpath + testname))
    {
    testname = Path.GetFileNameWithoutExtension(filename) + "_" + ai++ + Path.GetExtension(filename);
    }
    uploadFile.SaveAs(uploadpath + testname);
    URL = pathbase + testname;
    }
    }
    catch (Exception)
    {
    // 未知错误
    state = "u672au77e5u9519u8bef";
    URL = "";
    }
    return getUploadInfo();
    }
     
    /// <summary>
    /// 按照日期自动创建存储文件夹
    /// </summary>
    private void createFolder()
    {
    if (!Directory.Exists(uploadpath))
    {
    Directory.CreateDirectory(uploadpath);
    }
    }
     
    /// <summary>
    /// 文件类型检测
    /// </summary>
    /// <param name="filetype"></param>
    /// <returns></returns>
    private bool checkType(string[] filetype)
    {
    currentType = getFileExt();
    return Array.IndexOf(filetype, currentType) == -1;
    }
     
    /// <summary>
    /// 获取文件扩展名
    /// </summary>
    /// <returns></returns>
    private string getFileExt()
    {
    string[] temp = uploadFile.FileName.Split('.');
    return "." + temp[temp.Length - 1].ToLower();
    }
     
    /// <summary>
    /// 文件大小检测
    /// </summary>
    /// <param name="size"></param>
    /// <returns></returns>
    private bool checkSize(int size)
    {
    return uploadFile.ContentLength >= (size * 1024 * 1024);
    }
     
    /// <summary>
    /// 获取上传信息
    /// </summary>
    /// <returns></returns>
    private Hashtable getUploadInfo()
    {
    Hashtable infoList = new Hashtable();
     
    infoList.Add("state", state);
    infoList.Add("url", URL);
     
    if (currentType != null)
    infoList.Add("currentType", currentType);
    if (originalName != null)
    infoList.Add("originalName", originalName);
    return infoList;
    }
     
    /// <summary>
    /// 重命名文件
    /// </summary>
    /// <returns></returns>
    private string reName()
    {
    return System.Guid.NewGuid() + getFileExt();
    }
     
    /// <summary>
    /// 删除存储文件夹
    /// </summary>
    /// <param name="path"></param>
    public void deleteFolder(string path)
    {
    if (Directory.Exists(path))
    {
    Directory.Delete(path, true);
    }
    }
    }
    public static class NameFormater
    {
    public static string Format(string format, string filename)
    {
    if (String.IsNullOrWhiteSpace(format))
    {
    format = "{filename}{rand:6}";
    }
    string ext = Path.GetExtension(filename);
    filename = Path.GetFileNameWithoutExtension(filename);
    format = format.Replace("{filename}", filename);
    format = new Regex(@"{rand(:?)(d+)}", RegexOptions.Compiled).Replace(format, new MatchEvaluator(delegate (Match match)
    {
    var digit = 6;
    if (match.Groups.Count > 2)
    {
    digit = Convert.ToInt32(match.Groups[2].Value);
    }
    var rand = new Random();
    return rand.Next((int)Math.Pow(10, digit), (int)Math.Pow(10, digit + 1)).ToString();
    }));
    format = format.Replace("{time}", DateTime.Now.Ticks.ToString());
    format = format.Replace("{yyyy}", DateTime.Now.Year.ToString());
    format = format.Replace("{yy}", (DateTime.Now.Year % 100).ToString("D2"));
    format = format.Replace("{mm}", DateTime.Now.Month.ToString("D2"));
    format = format.Replace("{dd}", DateTime.Now.Day.ToString("D2"));
    format = format.Replace("{hh}", DateTime.Now.Hour.ToString("D2"));
    format = format.Replace("{ii}", DateTime.Now.Minute.ToString("D2"));
    format = format.Replace("{ss}", DateTime.Now.Second.ToString("D2"));
    var invalidPattern = new Regex(@"[\/:*?42<>|]");
    format = invalidPattern.Replace(format, "");
    return format + ext;
    }
     
    }
     
    &nbsp;

    lesg.cn,http://www.lesg.cn/netdaima/net/2017-990.html

    下面是demo下载地址:

    点击此处下载demo

  • 相关阅读:
    Linux Shell tr 命令详解
    Shell统计每个单词出现的个数
    启明4-29团队进度博客
    启明4-28团队进度博客
    启明4-27团队进度博客
    启明4-26团队进度博客
    启明4-25团队进度博客
    启明4-24团队博客
    每日总结8
    启明4-23团队进度博客
  • 原文地址:https://www.cnblogs.com/wcgsir/p/6292042.html
Copyright © 2020-2023  润新知