C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)

图片上传时我们进场用到的一个功能今天将他整理了一下写了个demo希望对大家有用

该demo分为如下

1.上传至至服务器文件夹

2.上传至阿里云oss

3.百度webupload上传图片

效果图如下:

 

首先讲解一下后台代码

(1)上传至服务器存储

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ImageUpLoad.Controllers
{
    public class UpLoadController : Controller
    {

       //定义存储文件夹
        private string SavePath
        {
            get
            {
                return "/Register/";
            }
        }

        #region uploadJson


        public ActionResult NewUploadImg()
        {
          
            //文件保存目录URL
            var saveUrl = SavePath;

            //定义允许上传的文件扩展名
            var extTable = new Hashtable
            {
            {"image", "gif,jpg,jpeg,png,bmp"}
            };
            //最大文件大小
            const int maxSize = 4194304;
            var imgFile = Request.Files[0];

            //HttpPostedFile imgFile = context.Request.Files["imgFile"];

            if (imgFile == null)
            {
                return NewShowError("请选择文件。", true);
            }

            var dirPath = Server.MapPath(SavePath);
            if (!Directory.Exists(dirPath))
            {
                //return ShowError("上传目录不存在。" + dirPath);
                Directory.CreateDirectory(dirPath);
            }

            var dirName = Request.QueryString["dir"];
            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }

            if (!extTable.ContainsKey(dirName))
            {
                return NewShowError("目录名不正确。", true);
            }

            var fileName = imgFile.FileName;
            var extension = Path.GetExtension(fileName);
            if (extension == null)
            {
                return NewShowError("extension == null", true);
            }

            var fileExt = extension.ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return NewShowError("上传文件大小超过限制。", true);
            }

            if (String.IsNullOrEmpty(fileExt) ||
            Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return NewShowError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。", true);
            }

            //创建文件夹
            dirPath += dirName + "/";
            saveUrl += dirName + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            dirPath += ymd + "/";
            saveUrl += ymd + "/";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            var newFileName = DateTime.Now.ToString("HHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            var filePath = dirPath + newFileName;

            imgFile.SaveAs(filePath);
            var fileUrl = saveUrl + newFileName;
          
            var hash = new Hashtable();
           
            return NewShowError(fileUrl, true);
           
        }


        private JsonResult NewShowError(string message, bool isImg)
        {
            var hash = new Hashtable();
            hash["mess"] = message;
            hash["isImg"] = isImg;

            return Json(hash, "text/html;charset=UTF-8");
        }

        #endregion


        //删除文件
        public ActionResult DeleteImg(string fileSrc)
        {
            var dirPath = Server.MapPath(fileSrc);
            if (System.IO.File.Exists(dirPath))
            {
                System.IO.File.Delete(dirPath);
            }

            return Json("");
        }
    }
}

(2)上传至oss服务器

using Aliyun.OSS;
using Aliyun.OSS.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace ImageUpLoad.Controllers
{
    public class NetUpLoadController : Controller
    {
        static string bucketName = Config.bucketName;//oss bucketName
        static string accessKeyId = Config.AccessKeyId;//阿里云 aceesskeyid
        static string accessKeySecret = Config.AccessKeySecret;//阿里云 AccessKeySecret
        static string endpoint = Config.Endpoint;//oss Endpoint
        static OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);

        static AutoResetEvent _event = new AutoResetEvent(false);
        static HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();

        #region uploadJson

      
     
        public ActionResult NewUploadImg()
        {
            string time = DateTime.Now.ToString("yyyy-MM-dd");

            string NewsavePath = "Register/";

            //文件保存目录URL
            var saveUrl = NewsavePath;

            //定义允许上传的文件扩展名
            var extTable = new Hashtable
            {
            {"image", "gif,jpg,jpeg,png,bmp,pdf"}
            };
            //最大文件大小
            const int maxSize = 15728640;
            var imgFile = Request.Files[0];



            if (imgFile == null)
            {
                return NewShowError("请上传出错,选择文件。", true);
            }
            var dirName = Request.QueryString["dir"];
            if (String.IsNullOrEmpty(dirName))
            {
                dirName = "image";
            }

            if (!extTable.ContainsKey(dirName))
            {
                return NewShowError("上传出错,目录名不正确。", true);
            }

            var fileName = imgFile.FileName;
            var extension = Path.GetExtension(fileName);
            if (extension == null)
            {
                return NewShowError("上传出错,extension == null", true);
            }

            var fileExt = extension.ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                return NewShowError("上传出错,上传文件大小超过限制。", true);
            }

            if (String.IsNullOrEmpty(fileExt) ||
            Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return NewShowError("上传出错,上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。", false);
            }

            //创建文件夹
            saveUrl += dirName + "/";
            var ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
            saveUrl += ymd + "/";
            var newFileName = DateTime.Now.ToString("HHmmssffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            var filePath = saveUrl + newFileName;
            var fileUrl = "/" + saveUrl + newFileName;

            var hash = new Hashtable();
            try
            {

                client.PutObject(bucketName, filePath, imgFile.InputStream);

                //由于我的域名地址是oss前缀是https://quicktouch.oss-cn-beijing.aliyuncs.com
                //这里返回前台的时候加上去
                return NewShowError("https://quicktouch.oss-cn-beijing.aliyuncs.com"+fileUrl, true);
                
            }
            catch (OssException ex)
            {
                hash["error"] = 1;
                hash["url"] = ex.Message;
                return NewShowError("上传出错," + ex.Message, true);

            }
            catch (Exception ex)
            {
                hash["error"] = 1;
                hash["url"] = ex.Message;
                return NewShowError("上传出错," + ex.Message, true);
            }

        }

   
        private JsonResult NewShowError(string message, bool isImg)
        {
            var hash = new Hashtable();
            hash["mess"] = message;
            hash["isImg"] = isImg;

            return Json(hash, "text/html;charset=UTF-8");
        }

        #endregion


     
        public ActionResult DeleteImg(string fileSrc)
        {
       
            try
            {   
                
                //去除图片地址中前缀
                int size = "https://quicktouch.oss-cn-beijing.aliyuncs.com/".Length;
                fileSrc = fileSrc.Substring(size, fileSrc.Length - size);
                client.DeleteObject(bucketName, fileSrc);
                //hash["error"] = 0;
                //hash["url"] = SiteURL + fileUrl;
            }
            catch (OssException ex)
            {


            }
            catch (Exception ex)
            {

            }
            return Json("");
        }

    }
}

(3)前端webupload代码

$('#upload-container').click(function (event) {
    $("#picker").find('input').click();
});
var uploader = WebUploader.create({
    auto: true,// 选完文件后,是否自动上传。
    swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',// swf文件路径
    server: '/UpLoad/NewUploadImg',// 文件接收服务端。
    dnd: '#upload-container',
    pick: '#picker',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
    multiple: true, // 选择多个
    chunked: true,// 开起分片上传。
    threads: 1, // 上传并发数。允许同时最大上传进程数。
    method: 'POST', // 文件上传方式,POST或者GET。
    fileSizeLimit: 1024 * 1024 * 100 * 100, //验证文件总大小是否超出限制, 超出则不允许加入队列。
    fileSingleSizeLimit: 1024 * 1024 * 100, //验证单个文件大小是否超出限制, 超出则不允许加入队列。
    fileVal: 'upload', // [默认值:'file'] 设置文件上传域的name。
});

uploader.on('fileQueued', function (file) {
    // 选中文件时要做的事情,比如在页面中显示选中的文件并添加到文件列表,获取文件的大小,文件类型等
    console.log(file.ext) // 获取文件的后缀
    console.log(file.size) // 获取文件的大小
    console.log(file.name);
    var html = '

文件名:' + file.name + '删除重试
'; $('#upload-list').append(html); }); uploader.on('uploadProgress', function (file, percentage) { console.log(percentage * 100 + '%'); var width = $('.upload-item').width(); $('.' + file.id).width(width * percentage); }); uploader.on('uploadSuccess', function (file, response) { console.log(file.id + "传输成功"); $("#" + file.id).val(response.mess); $("#img_" + file.id).attr('src', response.mess); }); uploader.on('uploadError', function (file) { console.log(file); console.log(file.id + 'upload error') }); $('#upload-list').on('click', '.upload-item .btn-delete', function () { // 从文件队列中删除某个文件id file_id = $(this).data('file_id'); // uploader.removeFile(file_id); // 标记文件状态为已取消 uploader.removeFile(file_id, true); // 从queue中删除 var urlsrc = $("#" + file_id).val(); $.ajax({ url: '/UpLoad/DeleteImg',//地址 type: 'Post',//类型 data: { fileSrc: urlsrc }, timeout: 2000,//超时 //请求成功 success: function (data, status) { //alert(status); }, //失败/超时 error: function (XMLHttpRequest, textStatus, errorThrown) { alert('删除失败'); //alert(errorThrown); } }) $("#upload_" + file_id).remove(); alert("删除成功"); }); $('#upload-list').on('click', '.btn-retry', function () { uploader.retry($(this).data('file_id')); }); uploader.on('uploadComplete', function (file) { console.log(uploader.getFiles()); });

注意我这里阿里云oss的读写方式是如果为私有的话需要加上读取时候的验证

 public ActionResult GetSignedUrl(string Imgurl)
        {
            string restr = "";
            try
            {
                OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                var request = new GeneratePresignedUriRequest(bucketName, Imgurl, SignHttpMethod.Get);//方式
                request.Expiration = DateTime.Now.AddMinutes(60);//有限时间
                var signedUrl = client.GeneratePresignedUri(request);
                restr = signedUrl.ToString();

                return Json(new { result = 1, data = restr, msg = "" }, JsonRequestBehavior.AllowGet);
                //return restr;
            }
            catch (Exception ex)
            {
                return Json(new { result = 0, data = "", msg = ex.Message }, JsonRequestBehavior.AllowGet);
            }

        }

这里需要注意的是如果为公共读的话我input值取的是完整url地址去存数据库

而私有读的话我只取了阿里云的文件地址并没有加上域名,因为私有的你要通过存储的文件地址去加上key和有效时间才能访问图片

 

 

最后需要源码都请扫码关注回复:图片上传
获取下载地址

C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)_第1张图片

 

你可能感兴趣的:(阿里云,HTML,c#)