这是我用于图片upload.its工作正常的以下代码。但问题是我想在更新现有图像(put方法)时从我的本地项目api文件夹(图像)中删除现有文件。
[Route("api/Products/PostProductImage")]
public Task<IEnumerable<string>> PostProductImage(int id)
{
if (Request.Content.IsMimeMultipartContent())
{
string fullPath = HttpContext.Current.Server.MapPath("~/Image/");
MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(fullPath);
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
Product product =db.Products.FirstOrDefault(a=>a.Id==id);
if (product == null) {
return "product not found";
}
product.ProductImage = File.ReadAllBytes(info.FullName);
db.SaveChanges();
return "File uploaded successfully!";
});
return fileInfo;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
}
}`
那么我想在put方法中做出哪些更改来检查我的图像文件夹中是否存在的图像并保存到db。 这就是我的图片在Image folder
中保存的方式谢谢ebk
答案 0 :(得分:0)
@ebk检查以下代码。
//检查文件是否存在的代码,然后删除
if(File.Exists(i.LocalFileName))
{
File.Delete(i.LocalFileName);
}
//对检查扩展进行编码
string ext = Path.GetExtension(i.LocalFileName);
if(ext==".jpg" || ext ==".gif" || ext ==".png")
{
//code
}
//检查文件长度的代码
var info = new FileInfo(i.LocalFileName);
var fileSizeInBytes = info.Length;
如果这有帮助您可以将其标记为已解决:)