我的代码将图像保存到数据库中,而其他数据将被忽略。
型号: 我的表名是一篇文章,其属性是 articleId,文章名称,文章图片和状态。
[HttpPost]
public async Task<HttpResponseMessage> Postdata()
{
article obj = new article();
List<string> savedFilePath = new List<string>();
// Check if the request contains multipart/form-data
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
//Get the path of folder where we want to upload all files.
string rootPath = HttpContext.Current.Server.MapPath("~/Uploads");
var provider = new MultipartFileStreamProvider(rootPath);
// Read the form data.
//If any error(Cancelled or any fault) occurred during file read , return internal server error
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
foreach (MultipartFileData dataitem in provider.FileData)
{
try
{
//Replace / from file name
string name = dataitem.Headers.ContentDisposition.FileName.Replace("\"", "");
//Create New file name using GUID to prevent duplicate file name
string newFileName = Guid.NewGuid() + Path.GetExtension(name);
//Move file from current location to target folder.
File.Move(dataitem.LocalFileName, Path.Combine(rootPath, newFileName));
string articlename = dataitem.Headers.ContentDisposition.Name;
string articlesutus = dataitem.Headers.ContentDisposition.FileNameStar;
obj.articleimage = newFileName;
obj.articlename = articlename;
obj.articlestatus = articlesutus;
_context.SaveChanges();
}
catch (Exception ex)
{
string message = ex.Message;
}
}
return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
});
return await task;
}