【问题标题】:Using stream with fileupload manipulating the result somehow使用带有文件上传的流以某种方式操纵结果
【发布时间】:2012-09-27 12:54:05
【问题描述】:

突然显示之前显示的图片停止显示在页面上并检查文件夹 * 当我单击它们时发现图像不显示。调试我的代码,我发现注释行导致了它。下面的代码是否无论如何都在操纵流?

public ActionResult UploadPhoto(UserPhotoUploadModel photoFileModel)
{
        HttpPostedFileBase photoFile = photoFileModel.PhotoFile;
    string uploadPath = Server.MapPath("~/Content/users/photos");
    string autoFileName = String.Format("{0}_{1}", Guid.NewGuid().ToString(), filename);
    string fileDestName = Path.Combine(uploadPath, autoFileName);

    //Starting from here is where the issue lies
    Stream imgStream = photoFile.InputStream;
    using (imgStream)
    {
        Image img = Bitmap.FromStream(imgStream);
        int width = img.Width;
        int height = img.Height;

        if (width > 100 || height > 100)
        {
            ModelState.AddModelError("PhotoFile", "Photo dimension should be 100 by 100 or less");
            return View(photoFileModel);
        }
    }
    //the issue ends here

    photoFile.SaveAs(fileDestName);

    return RedirectToAction("Profile", new {id = loggedinUser.ProviderUserKey});
}

保存的文件具有正确的图像扩展名,例如JPG。我正在使用流来确定上传图像的尺寸。

注释部分是导致此问题的原因。如何在输入流完好无损的情况下执行此操作?

谢谢。

【问题讨论】:

  • 没有注释区域,图像保存完美,但是当我添加它时,图像保存但空白/或不是真实图像,因此它不会显示在浏览器中。我认为using 块在photoFile.SaveAs(fileDestName) 被调用之前清除了流。我知道这一点是因为将 photoFile.SaveAs(fileDestName) 移动到 using 有效
  • 我怎样才能防止流被篡改,因为很明显,垃圾/什么都没有保存到文件中 - 文件存在于位置但不是有效的图像文件

标签: c# .net asp.net-mvc-3 image-processing file-upload


【解决方案1】:

问题出在这一行:

 return View(photoFileModel);

当代码到达这一行时,它会退出该方法。因此,这一行没有被执行:

photoFile.SaveAs(fileDestName);  

【讨论】:

  • 不!文件保存为空或无效的图像内容
  • 声明 photoFile 时会创建空文件或无效文件。注释掉 return View(photoFileModel);并测试它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多