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.
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.
Related
Is it possible not to show Open/Save dialog? I would like to save the pdf file straight to specific disk location on client PC.
Yes, you can write the file directly to disk without the use of a save dialog. All you need is a directory path to write too.
string path = "C:\YourDirectoryPathHere";
System.IO.File.WriteAllBytes(Path.Combine(path, "NameYourFile.pdf"), myPDF);
This assumes myPDF is a byte[].
I'm wondering if it's possible to read from a bytestream without saving it.
I have a file, wich is a PDF that's in a mailbox. Through code I can access this mailbox and read out the attachements in it (the pdf's) At that point every pdf is in a bystream.
For now I just save it locally to test if my code works. But I need to work without saving the file.
Is there a way so I can get data from that file without saving. I need to process the first page and find the image in there (which is a qr code).
I have code to do this from a local file, but I want this to be directly from on of those in the bystreams.
Can I store the bytesteam in something like an object or a list of bytestreams and use that?
I have an ASP.NET web application that allows the user to upload a file from his PC to a SQL Server database (which is later used to generate an image for an tag). Is there an "easy" way to test the image within .NET to validate that it does not contain anything malicious before saving it?
Right now, I use this:
MemoryStream F = new MemoryStream();
Bitmap TestBitmap = new Bitmap(Filename);
TestBitmap.Save(F, System.Drawing.Imaging.ImageFormat.Png);
int PhotoSize = (int)F.Length;
Photo = new byte[PhotoSize];
F.Seek(0, SeekOrigin.Begin);
int BytesRead = F.Read(Photo, 0, PhotoSize);
F.Close();
Creating TestBitmap fails if it is not an image (e.g. if Filename is the name of a text file), but apparently this doesn't stop a file that is an image with malicious code appended to it from loading as an image, so saving it as a MemoryStream and then writing the stream to a byte array (which is later saved in the database) supposedly fixes this.
To avoid people pass programs and other information's using the ability to upload photos to your site you can do two main steps.
Read and save again the image with your code to remove anything elst.
Limit the size of each image to a logical number.
To avoid some one upload bad code and run it on your server you keep an isolate folder with out permission to run anything. More information's about that on:
I've been hacked. Evil aspx file uploaded called AspxSpy. They're still trying. Help me trap them‼
And a general topic on the same subject: Preparing an ASP.Net website for penetration testing
I am using file upload mechanism to upload file for an employee and converting it into byte[] and passing it to varBinary(Max) to store into database.
Now I what I have to do is, if any file is already uploaded for employee, simply read it from table and show file name. I have only one column to store a file and which is of type VarBinary.
Is it possible to get all file information from VarBinary field?
Any other way around, please let me know.
If you're not storing the filename, you can't retrieve it.
(Unless the file itself contains its filename in which case you'd need to parse the blob's contents.)
If the name of the file (and any other data about the file that's not part of the file's byte data) needs to be used later, then you need to save that data as well. I'd recommend adding a column for the file name, perhaps one for its type (mime type or something like that for properly sending it back to the client's browser, etc.) and maybe even one for size so you don't have to calculate that on the fly for each file (useful when displaying a grid of files and not wanting to touch the large blob field in the query that populates the grid).
Try to stay away from using the file name for system-internal identity purposes. It's fine for allowing the users to search for a file by name, select it, etc. But when actually making the request to the server to display the file it's better to use a simple integer primary key from the table to actually identify it. (On a side note, it's probably a good idea to put a unique constraint on the file name column.)
If you also need help displaying the file to the user, you'll probably want to take the approach that's tried and true for displaying images from a database. Basically it involves having a resource (generally an .aspx page, but could just as well be an HttpHandler instead) which accepts the file ID as a query string parameter and outputs the file.
This resource would have no UI (remove everything from the .aspx except the Page directive) and would manually manipulate the response headers (this is where you'd set the content type from the file's type), write the byte stream to the client, and end the response. From the client's perspective, something like ~/MyContent/MyFile.aspx?fileID=123 would be the file. (You can suggest a file name to the browser for saving purposes in the response headers, which you'd probably want to do with the file's stored name.)
There's no shortage of quick tutorials (some several years old, it's been around for a while) on how to do this with images. Just remember that there's essentially no difference from the server's perspective if it's an image or any other kind of file. All the server needs to do is send the type in the response headers and write the file's bytes to the client. How the client handles the file is up to the browser. In the vast majority of cases, the browser will know what to do (display an image, display via a plugin a PDF, save a .doc, etc.).
i am trying to uplaod the file . before that i need to check for the file type and size before saving into the specified folder.
i need allow user only upload .jpg, .bmp, .swf,.png,.tiff,
no other fiel like .txt, pdf, .doc and need to check file size is always less than 1 MB. can we do this in javascript or c# coding
2: and before saving the file i need to check if there is any file with a same name in the folder if it is there than alret the user telling a file name exits
and should rename the file
any solution on this would be great
thank you
As for checking the file size and extension prior to uploading, you'll need to use some form of client side control for such. I'd recommend something like http://swfupload.org/.
As for checking to see if the same file name exists on the server prior, you'll need to use one of the pre-upload events from such a component to make an ajax call to the server to verify such.
You can use regular expression to check file type
<asp:RegularExpressionValidator ID="rexpImageE" Display="Dynamic" runat="server"
ControlToValidate="fup1" ErrorMessage="Only .gif, .jpg, .jpeg, .png, .tiff"
ValidationExpression="(.*\.([Gg][Ii][Ff])|.*\.([Jj][Pp][Gg])|.*\.([Bb][Mm][Pp])|.*\.([pP][nN][gG])|.*\.([tT][iI][iI][fF])$)"></asp:RegularExpressionValidator>
and you can check file size on server side like
if (fup1.PostedFile.ContentLength > lengthInBytes)
{
//your message
return;
}
You can only check filename and size after the file is sent to the server in C#.
You can use the FileName property to check the name. To get the file's extension, you can write Path.GetExtension(upload.FileName). Note that the fact that the file's extension is jpg doesn't mean that it's actually a JPEG image.
To check whether the file already exists, write File.Exists(Path.Combine(#"Your folder", upload.FileName))
To get the size in bytes, check upload.PostedFile.ContentLength.
You can find the correct way to do this on MSDN.
Here's a quick snippet which checks the file type:
if (bannerImageUpload.HasFile)
{
if (bannerFileExt == ".jpg")
{
Stream bannerFileStream = bannerImageUpload.PostedFile.InputStream;
bannerFileData = new byte[bannerImageUpload.PostedFile.ContentLength];
bannerFileStream.Read(bannerFileData, 0,
bannerImageUpload.PostedFile.ContentLength);
}
}
It's probably easier to use a RegularExpressionValidator to do this on the client. Note the use of the ContentLength property. Use File.Exists to check directory folder for any existing file with same name as explained by SLaks :-)