asp.net webapi 多文件上传

时间:2022-05-22 11:50:26

使用enctype="multipart/form-data"来进行操作

        /// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
[HttpPost]
[Token]
[Route("User/Upload")]
public async Task<HttpResponseMessage> Upload()
{
APIUpload apiUpload = new APIUpload();
var provider = await Request.Content.ReadAsMultipartAsync();
List<string> uploadedImages = new List<string>(provider.Contents.Count);
foreach (var item in provider.Contents)
{
if (item.Headers.ContentDisposition.FileName != null)
{
var data = await item.ReadAsByteArrayAsync();
//将流存放到阿里oss
string imageUrl = apiUpload.SavePlayImage(data);
ZBBlackboard blackboard = new ZBBlackboard();
uploadedImages.Add(imageUrl);
}
}
List<ZBBlackboard> blackboards = new List<ZBBlackboard>(uploadedImages.Count);
using (CMSDataContext context = DataContextFactory.CreateCMS())
{
int maxId = 0;
if (context.ZBBlackboard.Count() != 0)
{
maxId = context.ZBBlackboard.Max(b => b.ID);
}
foreach (string imageUrl in uploadedImages)
{
ZBBlackboard blackboard = new ZBBlackboard();
blackboard.ID = ++maxId;
blackboard.ImgUrl = imageUrl;
blackboards.Add(blackboard);
}
context.ZBBlackboard.InsertAllOnSubmit<ZBBlackboard>(blackboards);
context.SubmitChanges();
}
string token = LoginStatusHelper.GetNewLoginStatus(this.Request);
return this.Request.CreateResponse<APIResponseData>(APIResponseData.GetResponse(200, data: new { Images = blackboards }, token: token));
}