c# - 为什么 .Save() 创建重复文件?
问题描述
我的项目从用户那里获取一个上传的文件,以及来自 JCrop 的一些数据点,并将图像裁剪到选定的部分。然后,裁剪后的图像被赋予一个新名称,并保存到服务器。但是,图像会两次保存到服务器,一次使用新名称,另一次使用完全不同的名称。
控制器
[HttpPost]
[ValidateAntiForgeryToken]
[ValidImageFile]
public ActionResult _Image(ImageViewModel VM)
{
if (ModelState.IsValid)
{
//Convert from HttpPostedBase to WebImage, then crop the image
byte[] data;
using (Stream inputStream = VM.uploadFile.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
var Image = new WebImage(data);
int T = VM.y1;
int L = VM.x1;
int B = Image.Height - VM.y2;
int R = Image.Width - VM.x2;
Image.Crop(T, L, B, R);
//if the user already has an image for their character, delete it.
string oldImage = HttpContext.Server.MapPath(db.Characters.Find(VM.Id).imagePath);
if (System.IO.File.Exists(oldImage))
{
System.IO.File.Delete(oldImage);
}
//generate random file name path, save file to server.
var fileName = Guid.NewGuid().ToString();
var filePath = Path.Combine("/Content/Images/charPhoto/", fileName);
var uploadUrl = HttpContext.Server.MapPath(filePath);
Image.Save(uploadUrl);
//save file path to db.
filePath = filePath + "." + Image.ImageFormat;
db.Characters.Find(VM.Id).imagePath = filePath;
db.SaveChanges();
//returns the image path to jQuery.
return Content(filePath);
}
return View();
}
视图模型
public class ImageViewModel
{
public Guid? Id { get; set; }
public string ImagePath { get; set; }
public HttpPostedFileBase uploadFile { get; set; }
[Required]
public int x1 { get; set; }
[Required]
public int y1 { get; set; }
[Required]
public int x2 { get; set; }
[Required]
public int y2 { get; set; }
}
重复证明:
谁能向我解释为什么会这样?这是出于数据备份目的而有意使用的 WebImage 部分吗?如果没有,我做错了什么,我应该怎么做?
解决方案
我的天啊
string oldImage = db.Characters.Find(VM.Id).imagePath;
if (System.IO.File.Exists(HttpContext.Server.MapPath(oldImage)))
{
System.IO.File.Delete(HttpContext.Server.MapPath(oldImage));
}
var filePath = Path.Combine("/Content/Images/charPhoto/", Guid.NewGuid().ToString() + "." + Image.ImageFormat);
Image.Save(HttpContext.Server.MapPath(filePath));
//save file path to db.
db.Characters.Find(VM.Id).imagePath = filePath;
db.SaveChanges();
//returns the image path to jQuery.
return Content(filePath);
推荐阅读
- javascript - 使用 PHP / Javascript 将具有最小差异值的用户配对
- javascript - 延迟没有更快地加载页面
- azure - 从 Azure 中的 webapp 中删除虚拟应用程序/目录 - powershell
- c - 尝试 scanf 但无法访问它的值,除非输入另一个值
- sql - Sql server xpath 条件查询
- android - 有没有办法在 OnPause 事件或类似于 Android 中的 SavedInstanceState 的东西上保存科尔多瓦应用程序实例
- database - 使用查询将数据复制到 postgresql 中的 json 文件中时,将单个“\”的记录替换为“\\”
- lua - 传递给 Pandoc 的变量可以在 lua 过滤器中使用吗?
- c# - C# 类对象列表更改以匹配最后一个对象?
- html - 高度/宽度为 100% 的 DIV 中的 iFrame