Using stream with fileupload manipulating the resu

2019-09-07 05:49发布

问题:

Suddenly pictures that was showing before stopped showing on the page and checking the folder * discovered the image don't show when I click on them. Debugging my code I found the commented lines were causing it. Was the code below manipulating the stream in anyway?

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});
}

The saved files had the right image extension e.g. JPG. Am using the stream to determine the dimension of the uploaded image.

The commented portion is what is causing this issue. How can I do this with the Input stream still intact?

Thanks.

回答1:

The problem is this line:

 return View(photoFileModel);

When the code hits this line it exits out of the method. Therefore, this line is not executed:

photoFile.SaveAs(fileDestName);