圖片上傳時我們進場用到的一個功能今天將他整理了一下寫了個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 = '<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 () {
// 從文件隊列中刪除某個文件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和有效時間才能訪問圖片
最後需要源碼都請掃碼關注回覆:圖片上傳
獲取下載地址