上传图片:
前端为H+框架
引用class:
<link href="@Url.Content("~/Content/Hplus/css/plugins/webuploader/webuploader.css")" rel="stylesheet">
上传图片HTML代码:
<label class="col-sm-2 control-label">文章图片:</label>
<div class="col-sm-4">
<!--dom结构部分-->
<div id="uploader-demo">
<!--用来存放item-->
<div id="fileList" class="uploader-list"></div>
<div id="filePicker">选择图片</div>
</div>
</div>
引用JS:
<script src="~/Content/Hplus/js/plugins/webuploader/webuploader.js"></script>
JS上传代码:
var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
// 添加全局站点信息
var BASE_URL = 'js/plugins/webuploader';
// 图片上传demo
jQuery(function () {
var $ = jQuery,
$list = $('#fileList'),
// 优化retina, 在retina下这个值是2
ratio = window.devicePixelRatio || 1,
// 缩略图大小
thumbnailWidth = 100 * ratio,
thumbnailHeight = 100 * ratio,
// Web Uploader实例
uploader;
// 初始化Web Uploader
uploader = WebUploader.create({
// 自动上传。
auto: true,
// swf文件路径
swf: applicationPath + BASE_URL + '/Uploader.swf',
// 文件接收服务端。
server: applicationPath + '/ContentManager/ImgSubmit',
// 选择文件的按钮。可选。
// 内部根据当前运行是创建,可能是input元素,也可能是flash.
pick: '#filePicker',
// 只允许选择文件,可选。
accept: {
title: 'Images',
extensions: 'gif,jpg,jpeg,bmp,png',
mimeTypes: 'image/*'
}
});
uploader.on('ready', function (file) {
var $li = $(
'<div id="img" class="file-item thumbnail">' +
'<img id="img1"></div>'
),
$img = $li.find('img');
var src = "";
if ($("#ImageUrl").val() != "" && $("#ImageUrl").val() != "undefined") {
src = @System.Configuration.ConfigurationManager.AppSettings["ImagePath"] +$("#ImageUrl").val();
}
else {
src = "";
}
if (src != "" && src != undefined) {
$list.append($li);
$img.attr('src', src);
$img.attr('width', '130');
$("#img1").click(function () {
var width = $("#img1").width();
if (width == 130) {
$img.attr('width', '100%');
}
else {
$img.attr('width', '130');
}
});
}
});
// 当有文件添加进来的时候
uploader.on('fileQueued', function (file) {
$("#img").remove();
var $li = $(
'<div id="divfile" class="file-item thumbnail">' +
'<img></div>'
),
$img = $li.find('img');
$list.html($li);
// 创建缩略图
uploader.makeThumb(file, function (error, src) {
if (error) {
$img.replaceWith('<span>不能预览</span>');
return;
}
$img.attr('src', src);
}, thumbnailWidth, thumbnailHeight);
});
// 文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress', function (file, percentage) {
var $li = $('#' + file.id),
$percent = $li.find('.progress span');
// 避免重复创建
if (!$percent.length) {
$percent = $('<p class="progress"><span></span></p>')
.appendTo($li)
.find('span');
}
$percent.css('width', percentage * 100 + '%');
});
// 文件上传成功,给item添加成功class, 用样式标记上传成功。
uploader.on('uploadSuccess', function (file, response) {
$('#' + file.id).addClass('upload-state-done');
var path = response.filePath;
$("#ImageUrl").val(path);
});
// 文件上传失败,显示上传出错。
uploader.on('uploadError', function (file) {
var $li = $('#' + file.id),
$error = $li.find('div.error');
// 避免重复创建
if (!$error.length) {
$error = $('<div class="error"></div>').appendTo($li);
}
$error.text('上传失败');
});
// 完成上传完了,成功或者失败,先删除进度条。
uploader.on('uploadComplete', function (file) {
$('#' + file.id).find('.progress').remove();
});
// 负责view的销毁
function removeFile(file) {
var $li = $('#' + file.id);
delete percentages[file.id];
updateTotalProgress();
$li.off().find('.file-panel').off().end().remove();
}
});
上传图片到阿里云oss
1、需要阿里云开通oss
2、需要创建AccessKey
#region 上传图片 - OSS
/// <summary>
/// 上传图片 - OSS
/// </summary>
/// <param name="param">参数{"UserID":"用户ID"}</param>
/// <returns></returns>
public JsonResult UploadImg(string param)
{
JObject jObject = JObject.Parse(param);
if (Convert.ToInt32(jObject["UserID"].ToString()) < 2)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "数据提交失败,请重新登陆后再试" }, JsonRequestBehavior.DenyGet);
}
//OSS的访问地址 阿里云概览中的EndPoint(地域节点) 如果做了绑定域名,则为绑定的域名
string endpoint = System.Configuration.ConfigurationManager.AppSettings["OOS_endpoint"];
//OSS的访问ID
string accessKeyId = System.Configuration.ConfigurationManager.AppSettings["OOS_accessKeyId"];
//OSS的访问密钥
string accessKeySecret = System.Configuration.ConfigurationManager.AppSettings["OOS_accessKeySecret"];
//bucket列表中的名称
String bucketName = System.Configuration.ConfigurationManager.AppSettings["OOS_bucketName"];
//文件路径 必须与阿里云oss中匹配
string filePathName = "Admin/Chat/";
try
{
HttpPostedFileBase file = Request.Files[0];
//文件名称
filePathName += Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
if (Path.GetExtension(file.FileName) != ".png" && Path.GetExtension(file.FileName) != ".jpg")
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "请上传正确的图片格式" }, JsonRequestBehavior.DenyGet);
}
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
// 上传文件。
client.PutObject(bucketName, filePathName, file.InputStream);
}
catch (Exception ex)
{
ErrLog.LogResult("异常描述" + ex.Message);
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = ex.Message }, JsonRequestBehavior.DenyGet);
}
object data = new
{
PictureUrl = filePathName
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "" }, JsonRequestBehavior.DenyGet);
}
#endregion
从OSS上下载图片
#region 文件下载
/// <summary>
/// OSS文件下载
/// </summary>
/// <param name="objectName">oss文件路径</param>
/// <param name="downloadFilename">下载路径</param>
/// <returns></returns>
public JsonResult OSSDownload(string objectName, string downloadFilename)
{
//OSS的访问地址
string endpoint = System.Configuration.ConfigurationManager.AppSettings["OOS_endpoint"];
//OSS的访问ID
string accessKeyId = System.Configuration.ConfigurationManager.AppSettings["OOS_accessKeyId"];
//OSS的访问密钥
string accessKeySecret = System.Configuration.ConfigurationManager.AppSettings["OOS_accessKeySecret"];
String bucketName = System.Configuration.ConfigurationManager.AppSettings["OOS_bucketName"];
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
var obj = client.GetObject(bucketName, objectName);
using (var requestStream = obj.Content)
{
byte[] buf = new byte[1024];
var fs = System.IO.File.Open(downloadFilename, FileMode.OpenOrCreate);
var len = 0;
// 通过输入流将文件的内容读取到文件或者内存中。
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
{
fs.Write(buf, 0, len);
}
fs.Close();
}
Console.WriteLine("Get object succeeded");
}
catch (Exception ex)
{
return Json(new
{
jsonrpc = "2.0",
id = -1,
filePath = ex.Message
}, JsonRequestBehavior.AllowGet);
}
return Json(new
{
jsonrpc = "2.0",
filePath = downloadFilename
}, JsonRequestBehavior.AllowGet);
}
#endregion
上传图片到本地服务器:
需要设置Upload文件夹的权限为最高权限,可上传以及下载
System.Configuration.ConfigurationManager.AppSettings[“ImagePath”] 为上传文件的文件夹在config中的配置
#region 图片上传 - 本地
/// <summary>
/// 图片上传 - 本地
/// </summary>
/// <param name="param">参数{"UserID":"登录会员ID","Type":"图片类型"}</param>
/// <returns></returns>
[HttpPost]
public JsonResult UploadMerchantPicture(string param)
{
JObject jObject = JObject.Parse(param);
if (Convert.ToInt32(jObject["UserID"].ToString()) < 2)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "数据提交失败,请重新登陆后再试" }, JsonRequestBehavior.DenyGet);
}
string savePath = string.Empty;
string PictureUrl = string.Empty;
switch (jObject["Type"].ToString())
{
case "tx":
savePath = System.Configuration.ConfigurationManager.AppSettings["ImagePath"] + "HeadPortrait/"; //会员头像
break;
default:
break;
}
HttpFileCollectionBase httpFileCollectionBase = Request.Files;
string Name = Guid.NewGuid().ToString();
try
{
if (httpFileCollectionBase.Count > 0)
{
if (!Directory.Exists(Server.MapPath(savePath)))
{
Directory.CreateDirectory(Server.MapPath(savePath));
}
PictureUrl = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + jObject["UserID"].ToString();
if ("pos".Equals(jObject["Type"].ToString()))
{
httpFileCollectionBase[0].SaveAs(Server.MapPath(savePath) + Name + ".jpg");
}
else
{
httpFileCollectionBase[0].SaveAs(Server.MapPath(savePath) + PictureUrl + ".jpg");
}
switch (jObject["Type"].ToString())
{
case "tx":
PictureUrl = "/Upload/HeadPortrait/" + PictureUrl + ".jpg";
break;
default:
break;
}
object data = new
{
PictureUrl = PictureUrl
};
return Json(new Result { DATA = data, ERROR_CODE = "-1", ERROR_MESSAGE = "" }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = "请拍照或选择一张图片" }, JsonRequestBehavior.DenyGet);
}
}
catch (Exception ex)
{
return Json(new Result { DATA = null, ERROR_CODE = "1", ERROR_MESSAGE = ex.Message }, JsonRequestBehavior.DenyGet);
}
}
#endregion