图片上传时我们进场用到的一个功能今天将他整理了一下写了个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 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;//定义允许上传的文件扩展名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");}#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,// 选完文件后,是否自动上传。swf: 'https://cdn.bootcss.com/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和有效时间才能访问图片

下载地址

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

  1. Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程

    Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程 原文:Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程 Asp.Net Cor ...

  2. 用纯ASP代码实现图片上传并存入数据库中

      用纯ASP代码实现图片上传并存入数据库中    热     ★ 用纯ASP代码实现图片上传并存入数据库中 用ASP编写网站应用程序时间长了,难免会遇到各式各样的问题,其中关于如何上传文件到服务器恐 ...

  3. MVC 图片上传 带进度条(转)

    MVC 图片上传小试笔记 form.js 这个插件已经是很有名的,结合MVC的html辅助方法异步上传就很简单了.jQuery Form Plugin :http://www.malsup.com/j ...

  4. 微信小程序 - 超详细 “纯前端“ 将文件上传到阿里云 OSS,最新阿里云 OSS 直传音视频、图片、word、excel、ppt、office 文档(全程无需后端,前端文件直传阿里云oss服务器)

    前言 网上的教程乱七八糟却文件少代码(并且没注释),而且都已经很老了,对于新手来说真的无从下手. 本文站在新手小白的角度,实现微信小程序开发中,"前端直传" 上传文件到阿里云oss ...

  5. 微信小程序直接上传文件到阿里云OSS组件封装

    微信小程序直接上传文件到OSS 1. 封装公共方法 在根目录utils目录新建一个upload文件夹: // utils/upload/base64.jsvar base64EncodeChars = ...

  6. java上传文件至阿里云oss工具类

    第一步:引入oss maven坐标 <dependency><groupId>com.aliyun.oss</groupId><artifactId>a ...

  7. 上传文件到阿里云OSS

    最近项目中有文件上传的功能,才发现阿里云oss真是个好东西. 在其中做了好多的权限设置,角色.子账户.bucket等等. web端进行文件上传有多种方式 一.无需临时授权(安全性较低) (一).拿到权 ...

  8. ASP.Net MVC3 图片上传详解(form.js,bootstrap)

    图片上传的插件很多,但很多时候还是不能切合我们的需求,我这里给大家分享个我用一个form,file实现上传四张图片的小demo.完全是用jquery前后交互,没有用插件. 最终效果图如下: 玩过花田人 ...

  9. .NET自定义多文件(图片)上传的实现方式

    目的:通过输入要显示传图片的数量,自动创建相对应数量的上传控件,进行一次性上传操作. 默认有一个上传控件,当输入2时并点击添加按钮后,下面又显示了2个控件,效果如下: 点击全部上传按钮后的效果: CS ...

最新文章

  1. FACEGOOD 推出10万点人脸关键点跟踪,重新定义工业级人脸3D重建
  2. 浅谈ASP.NET 缓存技术
  3. 初学python-字符串中引号的使用、input简介、强制类型转换、加减乘除简写、条件判断...
  4. spring中@Transaction注解解析
  5. #Node.js的fs导入遇到的问题和解决方案
  6. XCTF-高手进阶区:baby_web
  7. 微型计算机系统配置实训报告,微机配置方案设计实训报告2018
  8. oracle 删除空间不足,oracle表空间扩容、创建、删除(解决表空间不足问题)
  9. npm使用taobao镜像
  10. python做线性回归统计推断提取参数_概率分析方法与推断统计(来自我写的python书)...
  11. 神奇的CAReplicatorLayer
  12. linux 格式化 lvm2,LVM2
  13. 【Golang】Go语言defer用法大总结(含return返回机制)
  14. 唐宇迪机器学习课程笔记:随机森林
  15. 【机器学习】逻辑回归算法
  16. 六度分割理论和SNS
  17. 74HC165应用介绍
  18. Android Studio 快捷键整理
  19. OpenWrt -【记录】群辉NAS上安装软路由
  20. ActivityManager: Killing *pid + 包名*: excessive cpu 21890 during 300019 dur=45344791 limit=2

热门文章

  1. 前端学习(3251):dom的diff算法2
  2. 前端学习(3102):vue+element今日头条管理-hello-react案例
  3. [css] 如何将元素的所有css属性恢复为初始化状态?
  4. 工作322:uni-扩展运算符实现拼接合并操作
  5. [js] 写一个方法遍历指定对象的所有属性
  6. 前端学习(2698):重读vue电商网站19之处理图片预览操作
  7. 前端学习(2663):vue3.0的todolist
  8. 前端学习(2662):vue3.0的todolist制作演示
  9. 前端学习(2536) request和response
  10. “约见”面试官系列之常见面试题之第九十五篇之vue-router的组件组成(建议收藏)