ASP.NET Coreは7牛画像のアップロードを簡単に実現(FormDataとBase 64)
ASP.NET Coreは7牛画像のアップロードを簡単に実現(FormDataとBase 64)
七牛画像アップロードSDK(.NETバージョン):https://developer.qiniu.com/kodo/sdk/1237/csharp
JSアップロード画像サンプルコード:
$(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 = {};
//ベース64の生成
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
data.p_w_picpath_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);
};
});
});
七牛画像アップロードSDK(.NETバージョン):https://developer.qiniu.com/kodo/sdk/1237/csharp
UpoladService
サンプルコード:public class UpoladService : IUpoladService
{
private readonly static string[] _p_w_picpathExtensions = new string[] { ".jpg", ".png", ".gif", ".jpeg", ".bmp" };
private AppSettings _appSettings;
public UpoladService(IOptions appSettings)
{
_appSettings = appSettings.Value;
}
public async Task 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 (!_p_w_picpathExtensions.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 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 UploadByBase64([FromBody]JObject data, AppType appType)
{
var p_w_picpathBase64 = data["p_w_picpath_base64"].ToObject();
var fileName = data["file_name"].ToObject();
if (!string.IsNullOrWhiteSpace(p_w_picpathBase64))
{
var reg = new Regex("data:p_w_picpath/(.*);base64,");
p_w_picpathBase64 = reg.Replace(p_w_picpathBase64, "");
byte[] p_w_picpathByte = Convert.FromBase64String(p_w_picpathBase64);
var stream = new MemoryStream(p_w_picpathByte);
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アップロード画像サンプルコード:
$(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 = {};
//ベース64の生成
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function () {
data.p_w_picpath_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);
};
});
});