ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)
ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)
七牛图片上传 SDK(.NET 版本):https://developer.qiniu.com/kodo/sdk/1237/csharp
UpoladService
示例代码:
public class UpoladService : IUpoladService
{
private readonly static string[] _imageExtensions = new string[] { ".jpg", ".png", ".gif", ".jpeg", ".bmp" };
private AppSettings _appSettings;
public UpoladService(IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
}
public async Task<SubmitResult> UploadStream(Stream stream, string fileName, AppType appType)
{
if (stream == null)
{
return SubmitResult.Fail("图片为null");
}
if (string.IsNullOrWhiteSpace(fileName))
{
return SubmitResult.Fail("图片名称为空");
}
try
{
var extensionName = fileName.Substring(fileName.LastIndexOf("."));
if (!_imageExtensions.Contains(extensionName.ToLower()))
{
return SubmitResult.Fail("图片格式有误");
}
var generateFileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssfff-")}{Guid.NewGuid().GetHashCode().ToString().Replace("-", string.Empty)}{extensionName}";
var saveKey = $"wl/{appType.ToString().ToLower()}/{generateFileName}";
// 生成(上传)凭证时需要使用此Mac
// 这个示例单独使用了一个Settings类,其中包含AccessKey和SecretKey
// 实际应用中,请自行设置您的AccessKey和SecretKey
Mac mac = new Mac(_appSettings.AccessKey, _appSettings.SecretKey);
// 上传策略,参见
// https://developer.qiniu.com/kodo/manual/put-policy
PutPolicy putPolicy = new PutPolicy();
// 如果需要设置为"覆盖"上传(如果云端已有同名文件则覆盖),请使用 SCOPE = "BUCKET:KEY"
// putPolicy.Scope = bucket + ":" + saveKey;
putPolicy.Scope = _appSettings.Bucket;
// 上传策略有效期(对应于生成的凭证的有效期)
putPolicy.SetExpires(3600);
// 上传到云端多少天后自动删除该文件,如果不设置(即保持默认默认)则不删除
//putPolicy.DeleteAfterDays = 1;
// 生成上传凭证,参见
// https://developer.qiniu.com/kodo/manual/upload-token
string jstr = putPolicy.ToJsonString();
string token = Auth.CreateUploadToken(mac, jstr);
FormUploader fu = new FormUploader();
var result = await fu.UploadStreamAsync(stream, saveKey, token);
if (result.Code == 200)
{
return SubmitResult.Success($"{_appSettings.Domain}/{saveKey}");
}
return SubmitResult.Fail("上传失败");
}
catch (Exception ex)
{
return SubmitResult.Fail($"上传失败:{ex.Message}");
}
}
}
UploadController
示例代码:
[EnableCors("default")]
[Route("upload")]
public class UploadController : WebApiController
{
private IUpoladService _upoladService;
public UploadController(IUpoladService upoladService)
{
_upoladService = upoladService;
}
[Route("{appType}/stream")]
[HttpPost]
public async Task<IActionResult> UploadByStream(AppType appType)
{
if (Request.Form.Files.Count == 0)
{
return Fail("图片不存在");
}
var file = Request.Form.Files[0];
var result = await _upoladService.UploadStream(file.OpenReadStream(), file.FileName, appType);
if (result.IsSuccess)
{
return Ok(new { pic_url = result.Data, is_success = true });
}
return Fail(result.Message);
}
[Route("{appType}/base64")]
[HttpPost]
public async Task<IActionResult> UploadByBase64([FromBody]JObject data, AppType appType)
{
var imageBase64 = data["image_base64"].ToObject<string>();
var fileName = data["file_name"].ToObject<string>();
if (!string.IsNullOrWhiteSpace(imageBase64))
{
var reg = new Regex("data:image/(.*);base64,");
imageBase64 = reg.Replace(imageBase64, "");
byte[] imageByte = Convert.FromBase64String(imageBase64);
var stream = new MemoryStream(imageByte);
var result = await _upoladService.UploadStream(stream, fileName, appType);
if (result.IsSuccess)
{
return Ok(new { pic_url = result.Data, is_success = true });
}
return Fail(result.Message);
}
return Json(new { success = false, result = "请选择文件!" });
}
}
JS 上传图片示例代码:
<form method="post" enctype="multipart/form-data">
<input type="file" id="files"
name="files" multiple />
<input type="button"
id="uploadStream"
value="Upload Selected Files" />
<input type="button"
id="uploadBase64"
value="Upload Selected Files" />
</form>
<script>
$(document).ready(function () {
$("#upload").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: "http://localhost:5002/upload/avatar/stream",
processData: false,
contentType: false,
data: data,
success: function (data) {
if (data.is_success) {
console.log(data.pic);
}
else {
console.log(data.msg);
}
console.log(data);
},
error: function () {
console.log("There was error uploading files!");
}
});
});
$("#uploadBase64").click(function (evt) {
var fileUpload = $("#files").get(0);
var files = fileUpload.files;
var data = {};
//生成base64
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
data.image_base64 = reader.result;
data.file_name = files[0].name;
$.ajax({
type: "POST",
url: "http://localhost:5002/upload/avatar/base64",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
dataType: 'json',
success: function (data) {
if (data.is_success) {
console.log(data.pic);
}
else {
console.log(data.msg);
}
console.log(data);
},
error: function () {
console.log("There was error uploading files!");
}
});
return reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
});
});
</script>
作者:田园里的蟋蟀
微信公众号:你好架构
出处:http://www.cnblogs.com/xishuai/
公众号会不定时的分享有关架构的方方面面,包含并不局限于:Microservices(微服务)、Service Mesh(服务网格)、DDD/TDD、Spring Cloud、Dubbo、Service Fabric、Linkerd、Envoy、Istio、Conduit、Kubernetes、Docker、MacOS/Linux、Java、.NET Core/ASP.NET Core、Redis、RabbitMQ、MongoDB、GitLab、CI/CD(持续集成/持续部署)、DevOps等等。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
微信公众号:你好架构
出处:http://www.cnblogs.com/xishuai/
公众号会不定时的分享有关架构的方方面面,包含并不局限于:Microservices(微服务)、Service Mesh(服务网格)、DDD/TDD、Spring Cloud、Dubbo、Service Fabric、Linkerd、Envoy、Istio、Conduit、Kubernetes、Docker、MacOS/Linux、Java、.NET Core/ASP.NET Core、Redis、RabbitMQ、MongoDB、GitLab、CI/CD(持续集成/持续部署)、DevOps等等。
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。