zoukankan      html  css  js  c++  java
  • .net core 2.0 webuploader上传图片

    引入文件
    <link href="~/Scripts/webuploader-0.1.5/webuploader.css" rel="stylesheet" />
        <script src="~/Scripts/webuploader-0.1.5/webuploader.js"></script>

    html

     <div id="uploader-demo">
            <div id="filePicker" class="uploader-list"><img id="photo" style="50px;height:50px" src="/photo.jpg"></div>
        </div>
    css(可选,目的是把图片做成选择按钮,去掉背景色,为了美观)
    .uploader-list {
            width: 50px;
        }
        #filePicker .webuploader-pick{
            background: rgba(0,0,0,0);
            padding:0;
        }

    js

    function initUpload() {
                $list = $('#fileList');
                // 初始化Web Uploader
                var uploader = WebUploader.create({
    
                    // 选完文件后,是否自动上传。
                    auto: true,
    
                    // swf文件路径
                    swf: '~/Scripts/webuploader-0.1.5/Uploader.swf',
    
                    // 文件接收服务端。
                    server: '/FileUp.ashx?address=Photo',
    
                    // 选择文件的按钮。可选。
                    // 内部根据当前运行是创建,可能是input元素,也可能是flash.
                    pick: {
                        id: '#filePicker'
                    },
    
                    // 只允许选择图片文件。
                    accept: {
                        title: 'Images',
                        extensions: 'jpg,jpeg,png',
                        mimeTypes: 'image/jpg,image/jpeg,image/png'//不要写'image/*'
                    },
                    fileSingleSizeLimit: 1024 * 1024 * 10 //限制单个上传图片的大小(限制上传单张图片文件大小,单位是B,1M=1024000B)
                });
                // 当有文件添加进来的时候
                uploader.on('fileQueued', function (file) {
                    //start
                        //var $li = $(
                        //        '<div id="' + file.id + '" class="file-item thumbnail">' +
                        //            '<img>' +
                        //            '<div class="info">' + file.name + '</div>' +
                        //        '</div>'
                        //        ),
                        //$img = $li.find('img');
    
    
                        // $list为容器jQuery实例
                        //$list.append($li);
                    //end
                    //上面这些代码是后来注掉的,为了实现单个图片上传
                    var uploadimgWidth = $('#fileList').width();
                    var thumbnailWidth = uploadimgWidth;
                    var thumbnailHeight = thumbnailWidth;
    
                    // 创建缩略图
                    // 如果为非图片文件,可以不用调用此方法。
                    // thumbnailWidth x thumbnailHeight 为 100 x 100
                    uploader.makeThumb(file, function (error, src) {
                        if (error) {
                            $('#photo').replaceWith('<span>不能预览</span>');
                            return;
                        }
    
                        //$img.attr('src', src);
                        $('#photo').attr('src', src);//为了实现选择图片后显示选中的图片
                    }, thumbnailWidth, thumbnailHeight);
                });
                // 文件上传过程中创建进度条实时显示。
                uploader.on('uploadProgress', function (file, percentage) {
                    var $li = $('#' + file.id),
                        $percent = $li.find('.progress span');
    
                    // 避免重复创建
                    if (!$percent.length) {
                        $percent = $('<p class="progress"><span></span></p>')
                                .appendTo($li)
                                .find('span');
                    }
    
                    $percent.css('width', percentage * 100 + '%');
                });
    
                // 文件上传成功,给item添加成功class, 用样式标记上传成功。
                uploader.on('uploadSuccess', function (file,response) {//respoonse是后台返回的内容
                    $('#' + file.id).addClass('upload-state-done');
                });
    
                // 文件上传失败,显示上传出错。
                uploader.on('uploadError', function (file) {
                    var $li = $('#' + file.id),
                        $error = $li.find('div.error');
    
                    // 避免重复创建
                    if (!$error.length) {
                        $error = $('<div class="error"></div>').appendTo($li);
                    }
    
                    $error.text('上传失败');
                });
    
                // 完成上传完了,成功或者失败,先删除进度条。
                uploader.on('uploadComplete', function (file) {
                    $('#' + file.id).find('.progress').remove();
                });
            }

    后台(一般处理程序)

     
    context.Response.ContentType = "text/html";
    if (context.Request.Files.Count <= 0) { return; } //创建文件夹 string name = context.Request["address"]; string dicPath = context.Server.MapPath("/UploadFiles/" + name + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/"); if (!Directory.Exists(dicPath)) { Directory.CreateDirectory(dicPath); } //保存图片 HttpPostedFile img = context.Request.Files[0]; string ext = Path.GetExtension(img.FileName); string fileName = Guid.NewGuid().ToString() + ext; string filePath = Path.Combine(dicPath, fileName); img.SaveAs(filePath);
    context.Response.Write(urlPrev+fileName);
    .net core 2.0
    1. 前四步与上面相同
    2. 后台
     public IHostingEnvironment _hostingEnvironment{get;set;}
            public ActionResult UploadFile()
            {
               if (Request.Form.Files.Count <= 0)
                {
                    return Content("请选择图片");
                }
                string name = Request.Query["address"];
                string imgPath="\UploadFiles\" + name + "\" + DateTime.Now.Year + "\" + DateTime.Now.Month + "\" + DateTime.Now.Day + "\";
                string dicPath = _hostingEnvironment.WebRootPath+imgPath;
                if (!Directory.Exists(dicPath))
                {
                    Directory.CreateDirectory(dicPath);
                }
                var img = Request.Form.Files[0];
                if(img==null){
                    return Content("上传失败");
                }
                string ext = Path.GetExtension(img.FileName);
                //判断后缀是否是图片
                const string fileFilt = ".jpg|.jpeg|.png|";
                //判断后缀是否是图片
                if (ext == null)
                {
                    return Content("上传的文件没有后缀" );
                }
                if (fileFilt.IndexOf(ext.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    return Content("上传的文件不是图片");
                }
                string fileName = Guid.NewGuid().ToString() + ext;
                string filePath = Path.Combine(dicPath, fileName);
                using(FileStream fs = System.IO.File.Create(filePath)){
                    img.CopyTo(fs);
                    fs.Flush();
                }
                 return Content(imgPath+fileName);
            }
    .net core 2.0没有server.MapPath和SaveAs,需要使用IHostingEnvironment
     
     
     
  • 相关阅读:
    分分钟用上C#中的委托和事件
    AutoResetEvent详解
    C#跨线程调用
    多线程编程的注意事项
    C#中WinForm程序退出方法技巧总结
    用c#实现单链表(程序代码已经验证,完全正确)
    event & EventHandler
    Kubernetes理论02
    centos7 日志文件
    CentOS7 FTP安装与配置
  • 原文地址:https://www.cnblogs.com/xiaonangua/p/9173771.html
Copyright © 2011-2022 走看看