TGuimond
TGuimond

Reputation: 5487

asp.net image jpeg not saving correctly

I am trying to save a jpeg image in an uploads folder which has correct permissions setup. When I test the file is being saved (eg: images/uploads/Winter.jpg) but if I try to view the image in my browser or if I attempt to open the image using anything else the image does not display.

I think that the file is not being encoded correctly before saving it to disk but am not very experienced dealing with the saving of files, encoding. Does the below code look ok or do I need to encode the file being uploaded somehow before saving it to disk?

String imgPath = "newsletter\\images\\uploads\\";

String filename = System.IO.Path.GetFileName(upload.PostedFile.FileName);

filepath = imgPath + filename;

filepath = Request.PhysicalApplicationPath + filepath; 
upload.PostedFile.SaveAs(filepath);

The file saves to the correct folder but is only 150bytes in size. If I try to browse to the file and view it with an image viewer it does not display correctly.

Upvotes: 0

Views: 723

Answers (1)

Lilith River
Lilith River

Reputation: 16468

Encoding shouldn't be a problem - the raw data isn't changing. However, it's possible the browser isn't sending all the data, or that the upload control is deleting the data before you're saving it.

Make sure that you call .SaveAs() before the page begins unloading, and before any additional postbacks. I think we'll need to see more surrounding code to help further.

Another note - by allowing the existing file extension to be used, you're allowing users to upload .aspx files, which could subsequently be executed through a request. Safe filenames are GUIDs and whitelisted file extensions. Using un-sanitized uploaded path information is very dangerous. If you re-use filenames, sanitize them to alphanumerics.

Upvotes: 1

Related Questions