C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)
生活随笔
收集整理的這篇文章主要介紹了
C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
圖片上傳時(shí)我們進(jìn)場(chǎng)用到的一個(gè)功能今天將他整理了一下寫了個(gè)demo希望對(duì)大家有用
該demo分為如下
1.上傳至至服務(wù)器文件夾
2.上傳至阿里云oss
3.百度webupload上傳圖片
效果圖如下:
首先講解一下后臺(tái)代碼
(1)上傳至服務(wù)器存儲(chǔ)
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{//定義存儲(chǔ)文件夾private string SavePath{get{return "/Register/";}}#region uploadJsonpublic ActionResult NewUploadImg(){//文件保存目錄URLvar saveUrl = SavePath;//定義允許上傳的文件擴(kuò)展名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("請(qǐng)選擇文件。", 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("上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\n只允許" + ((String)extTable[dirName]) + "格式。", true);}//創(chuàng)建文件夾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服務(wù)器
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 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;//定義允許上傳的文件擴(kuò)展名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("請(qǐng)上傳出錯(cuò),選擇文件。", true);}var dirName = Request.QueryString["dir"];if (String.IsNullOrEmpty(dirName)){dirName = "image";}if (!extTable.ContainsKey(dirName)){return NewShowError("上傳出錯(cuò),目錄名不正確。", true);}var fileName = imgFile.FileName;var extension = Path.GetExtension(fileName);if (extension == null){return NewShowError("上傳出錯(cuò),extension == null", true);}var fileExt = extension.ToLower();if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize){return NewShowError("上傳出錯(cuò),上傳文件大小超過限制。", true);}if (String.IsNullOrEmpty(fileExt) ||Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1){return NewShowError("上傳出錯(cuò),上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\n只允許" + ((String)extTable[dirName]) + "格式。", false);}//創(chuàng)建文件夾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//這里返回前臺(tái)的時(shí)候加上去return NewShowError("https://quicktouch.oss-cn-beijing.aliyuncs.com"+fileUrl, true);}catch (OssException ex){hash["error"] = 1;hash["url"] = ex.Message;return NewShowError("上傳出錯(cuò)," + ex.Message, true);}catch (Exception ex){hash["error"] = 1;hash["url"] = ex.Message;return NewShowError("上傳出錯(cuò)," + 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-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,// 選完文件后,是否自動(dòng)上傳。swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',// swf文件路徑server: '/UpLoad/NewUploadImg',// 文件接收服務(wù)端。dnd: '#upload-container',pick: '#picker',// 內(nèi)部根據(jù)當(dāng)前運(yùn)行是創(chuàng)建,可能是input元素,也可能是flash. 這里是div的idmultiple: true, // 選擇多個(gè)chunked: true,// 開起分片上傳。threads: 1, // 上傳并發(fā)數(shù)。允許同時(shí)最大上傳進(jìn)程數(shù)。method: 'POST', // 文件上傳方式,POST或者GET。fileSizeLimit: 1024 * 1024 * 100 * 100, //驗(yàn)證文件總大小是否超出限制, 超出則不允許加入隊(duì)列。fileSingleSizeLimit: 1024 * 1024 * 100, //驗(yàn)證單個(gè)文件大小是否超出限制, 超出則不允許加入隊(duì)列。fileVal: 'upload', // [默認(rèn)值:'file'] 設(shè)置文件上傳域的name。 });uploader.on('fileQueued', function (file) {// 選中文件時(shí)要做的事情,比如在頁(yè)面中顯示選中的文件并添加到文件列表,獲取文件的大小,文件類型等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 () {// 從文件隊(duì)列中刪除某個(gè)文件idfile_id = $(this).data('file_id');// uploader.removeFile(file_id); // 標(biāo)記文件狀態(tài)為已取消uploader.removeFile(file_id, true); // 從queue中刪除var urlsrc = $("#" + file_id).val();$.ajax({url: '/UpLoad/DeleteImg',//地址type: 'Post',//類型data: { fileSrc: urlsrc },timeout: 2000,//超時(shí)//請(qǐng)求成功success: function (data, status) {//alert(status);},//失敗/超時(shí)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的讀寫方式是如果為私有的話需要加上讀取時(shí)候的驗(yàn)證
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);//有限時(shí)間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地址去存數(shù)據(jù)庫(kù)
而私有讀的話我只取了阿里云的文件地址并沒有加上域名,因?yàn)樗接械哪阋ㄟ^存儲(chǔ)的文件地址去加上key和有效時(shí)間才能訪問圖片
下載地址
總結(jié)
以上是生活随笔為你收集整理的C# ASP.NET MVC 图片上传的多种方式(存储至服务器文件夹,阿里云oss)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: license文件生成原理
- 下一篇: c# 两个数的加减乘除