checking for the file type(.txt,jpg,etc) and size before uploading
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 youAs 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 :-)
精彩评论