2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹 阿里云oss)

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

时间:2021-06-23 20:35:40

相关推荐

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 uploadJsonpublic ActionResult NewUploadImg(){//文件保存目录URLvar 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 mon;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 bucketNamestatic string accessKeyId = Config.AccessKeyId;//阿里云 aceesskeyidstatic string accessKeySecret = Config.AccessKeySecret;//阿里云 AccessKeySecretstatic string endpoint = Config.Endpoint;//oss Endpointstatic OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);static AutoResetEvent _event = new AutoResetEvent(false);static HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();#region uploadJsonpublic ActionResult NewUploadImg(){string time = DateTime.Now.ToString("yyyy-MM-dd");string NewsavePath = "Register/";//文件保存目录URLvar 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-//这里返回前台的时候加上去return NewShowError("https://quicktouch.oss-cn-"+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");}#endregionpublic ActionResult DeleteImg(string fileSrc){try{ //去除图片地址中前缀int size = "https://quicktouch.oss-cn-/".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: '/webuploader/0.1.1/Uploader.swf',// swf文件路径server: '/UpLoad/NewUploadImg',// 文件接收服务端。dnd: '#upload-container',pick: '#picker',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的idmultiple: 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 = '<div class="upload-item" id="upload_' + file.id + '" style="text-align:center"><img src="" id="img_' + file.id + '" style="width:50px;width:50px;"><br><input type="hidden" id="' + file.id + '"><span>文件名:' + file.name + '</span><span data-file_id="' + file.id + '" class="btn-delete">删除</span><span data-file_id="' + file.id + '" class="btn-retry">重试</span><div class="percentage ' + file.id + '" style="width: 0%;"></div></div>';$('#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 () {// 从文件队列中删除某个文件idfile_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和有效时间才能访问图片

下载地址

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。