博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
前后端文件上传
阅读量:7028 次
发布时间:2019-06-28

本文共 4003 字,大约阅读时间需要 13 分钟。

 

/*前端使用form-data post 多媒体文件,后端采用HttpFileCollection处理上传的文件

上传的文件临时保存本地后传至阿里云oos,上传成功返回oos的url地址,并将本地文件删除(可以直接传文件流而不需临存本地,C#版的oos通过文件流上传好像有点问题,所以采用了暂存本地通过路径上传)

*/

#region 图片上传

/// <summary>
/// 图片上传
/// </summary>
/// <returns></returns>
[HttpPost]
public IHttpActionResult UploadFile([FromUri]string sysAppId)
{
OperationResult response = new OperationResult
{
Code = OperationResultType.IllegalOperation,
Message = "请求非法"
};
// 是否请求包含multipart/form-data。
if (!Request.Content.IsMimeMultipartContent())
{
response.Message = "请求头格式必须为:multipart/form-data";
return Json(response);
}
HttpFileCollection filelist = HttpContext.Current.Request.Files;
if (filelist != null && filelist.Count > 0)
{
HttpPostedFile file = filelist[0];
if (string.IsNullOrWhiteSpace(file.FileName) || !file.FileName.Contains("."))
{
return Json(response);
}
var fileNameSplit = file.FileName.Trim(new[] { '"' }).Split('.');
string fileExName = fileNameSplit[fileNameSplit.Length - 1];
string fileName = string.Format(@"{0}.{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), fileExName);
string baseFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\FileUpload\\";
string filePath = baseFilePath + fileName;
try
{
file.SaveAs(filePath);
var proxy = new AliyunOssProxy();
string bucketName = "zyunuser";
var rsp = proxy.PutObjToBucket(bucketName, $"{MD5Helper.GetMD5(sysAppId, 16)}/{fileName}", filePath);
#region 删除文件
if (File.Exists(filePath))
{
File.Delete(filePath);
}
#endregion
if (rsp.IsSuccess)
{
response.Code = OperationResultType.Success;
response.Message = "上传成功";
response.AppendData = rsp.Url;
return Json(response);
}
}
catch (Exception ex)
{
response.Message = ex.Message;

LogHelper.Error("UploadFile-error", ex);

return Json(response);
}
}
return Json(response);
}

#endregion

 

//前端以base64数据上传文件

#region 图片上传(base64)

/// <summary>

/// 图片上传(base64)
/// </summary>
/// <param name="sysAppId">当前操作人id</param>
/// <returns></returns>
[HttpPost]
public IHttpActionResult UploadFileBase64([FromUri] string sysAppId = "")
{
OperationResult response = new OperationResult
{
Code = OperationResultType.IllegalOperation,
Message = "请求非法"
};
var base64string = HttpContext.Current.Request.Form["base64string"];

if (string.IsNullOrWhiteSpace(base64string))

{
response.Message = "参数base64string必传";
return Json(response);
}

string baseFilePath = AppDomain.CurrentDomain.BaseDirectory + "App_Data\\FileUpload\\";

string fileName = string.Format(@"b64img_{0}.{1}", DateTime.Now.ToString("yyyyMMddHHmmssfff"), "png");
string filePath = baseFilePath + fileName;

MemoryStream stream = null;

Bitmap btm = null;
try
{
var base64 = base64string.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
if (!XTools.Base64Utility.IsBase64String(base64))
{
return Json(response);
}

byte[] arr = Convert.FromBase64String(base64);

stream = new MemoryStream(arr, 0, arr.Length);

//Image mImage = Image.FromStream(stream);
btm = new Bitmap(stream);
btm.Save(filePath, ImageFormat.Png);
btm.Dispose();
stream.Dispose();

var proxy = new AliyunOssProxy();

string bucketName = "zyunuser";

LogHelper.Info($"UploadFile-info:{bucketName},{MD5Helper.GetMD5(sysAppId, 16)}/{fileName},{filePath}");

var rsp = proxy.PutObjToBucket(bucketName, $"{MD5Helper.GetMD5(sysAppId, 16)}/{fileName}", filePath);

if (rsp.IsSuccess)

{
response.Code = OperationResultType.Success;
response.Message = "上传成功";
response.AppendData = rsp.Url;
return Json(response);
}
}
catch (Exception ex)
{
response.Message = ex.Message;
LogHelper.Error("UploadFileBase64-error", ex, "CommonController", "UploadFileBase64");
response.Code = OperationResultType.Error;
return Json(response);
}
finally
{
if (null != btm)
{
btm.Dispose();
}
if (null != stream)
{
stream.Close();
stream.Dispose();
}
#region 删除文件
if (File.Exists(filePath))
{
File.Delete(filePath);
}
#endregion
}
return Json(response);
}

#endregion

转载于:https://www.cnblogs.com/zlj-rechio/p/9953515.html

你可能感兴趣的文章
python简易web服务器学习笔记(二)
查看>>
结束进程的批处理文件
查看>>
获取select option的text
查看>>
第九周作业
查看>>
python中几个常见的黑盒子之“字典dict” 与 “集合set”
查看>>
制作、解析带logo的二维码
查看>>
C# 中2个问号的作用。C#的??代表是什么意思
查看>>
CentOS下安装node
查看>>
for in,Object.keys()与for of的区别
查看>>
从源码编译Chrome(chromium)
查看>>
博客背景图片以及案例图片
查看>>
HYSBZ 4198 荷马史诗
查看>>
epoll中et+多线程模式中很重要的EPOLL_ONESHOT实验
查看>>
strptime和strptime函数理解
查看>>
微博数据调研
查看>>
Linux下硬盘分区
查看>>
java中 Excel表实现数据导入导出
查看>>
PHP str_replace() 和str_ireplace()函数
查看>>
什么是全栈工程师
查看>>
Html5新特性
查看>>