How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.
Related
I have an xml file which contain images url . i am verifying the url whether url is responsive or not. If url is not responsive then i am removing that url from xml. and saving all changes . but i am getting error like
'The process cannot access the file 'E:\1.xml' because it is being used by another process'
xmlTR = new XmlTextReader(#"E:\1.xml");
PrimaryXmlDoc.Load(xmlTR);
foreach (XmlNode node in PrimaryXmlDoc.SelectNodes("/fp-hotel/Images/Url"))
{
if (CheckUrlExists(node.InnerText))
{
}
else
{
XmlElement _xmlElement = PrimaryXmlDoc.DocumentElement;
node.ParentNode.RemoveChild(node);
}
}
PrimaryXmlDoc.Save(#"E:\1.xml");
I assume that you have to Close XmlTextReader before using it second time. If you don't do that, the previous instance will keep your file open and you won't be able to open it again.
EDIT: And that's what happens here is probably that you want to save file before closing it.
Add line:
xmlTR.Close();
before
PrimaryXmlDoc.Save(#"E:\1.xml");
I'm new to asp.net and I'm making a website with asp.net mvc 4 where user can upload any type of image(png, jpeg, gif) but system will save the image as a png format. I'm using WebImage helper. So far uploading is working fine but whenever system saves the image, filename looks like this, Filename.png.jpeg. Here is my codes from Controller,
if (file != null && file.ContentLength > 0)
{
string picName = "FileName";
WebImage img = new WebImage(file.InputStream);
if (img.Width > 265 || img.Height > 158)
{
img.Resize(265, 158);
}
string picExt = Path.GetExtension(file.FileName);
if (picExt == ".jpg")
{
picExt = ".png";
}
string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
img.Save(path);
}
How can I save the image as only png format no matter what user uploads in any format of image? Need this help badly. Tnx.
I had the same problem, and I just told it to ignore correct extension forcing.
The third parameter is bool forceCorrectExtension which is true by default. You don't need the second parameter since you manually set your extension.
img.Save(path, null, false);
Just ran into the same issue. Please see here:
WebImage.Save Method
Cognis is half correct and it will probably work like that. However, the 2nd parameter actually tells it what format to save as:
imageFormat Type: System.String The format to use when the image file
is saved, such as "gif", or "png".
A jpeg doesn't become a png simply because you change the extension. Unless the Save method knows to reformat based on extension (???), I would rather error on the side of caution by doing:
img.Save(path, "png", false);
I mean, when a user chooses the video file from their system, have the web-page already show them the files they want to upload.
I'm already using image file to preview using FileAPI JS. The same I want to do with FileAPI JS for video file.
(So, It must be work within my client side)
Thanks & answers are appreciated :)
You can either use FileReader or createObjectURL. They'll both get the job done, but FileReader has slightly broader support in browsers.
createObjectURL will run synchronously and return a Blob URL, a short string referencing the file in memory. and you can free it up immediately after you're done using it.
FileReader will run asynchronously, requiring a callback, providing a Data URI, a much longer string representing the whole file. This can be very big and will be freed from memory in Javascript garbage collection.
Here's an example that first tries createObjectURL and falls back to FileReader. (Please provide your own error checking, etc.)
var video = document.getElementById('video'),
input = document.getElementById('input');
input.addEventListener('change', function (evt) {
var reader = new window.FileReader(),
file = evt.target.files[0],
url;
reader = window.URL || window.webKitURL;
if (reader && reader.createObjectURL) {
url = reader.createObjectURL(file);
video.src = url;
reader.revokeObjectURL(url); //free up memory
return;
}
if (!window.FileReader) {
console.log('Sorry, not so much');
return;
}
reader = new window.FileReader();
reader.onload = function(evt) {
video.src = evt.target.result;
};
reader.readAsDataURL(file);
}, false);
Working example here: http://jsbin.com/isodes/1/edit
Mozilla has a more detailed article with instructions on how to upload once you've got your file.
IE10 supports both, but IE9 supports neither, so you'll have to fall back to a regular form upload without a preview.
i am using file upload control in server side when iam trying to get the file it is showing no file present
<asp:FileUpload ID="upldDocument" runat="server" />
string fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
if (upldDocument.HasFile)
{
}
i am getting a empty string as file extension and upldDocument.HasFile is returning false even after selecting a file.
what could be the reason??
Based on the posted code, I can only offer a best guess. There's not enough code posted to be sure what the problem is, but here's my best guess:
If you're not already, you need to check the HasFile property.
See here for a full example:
Edit - added
Using HasFile AFTER the bad code won't help. You need to put the code to get the extention inside an if statement so that it only attempts to read the extension if there IS a file.
string fileExtension = "";
if (upldDocument.HasFile)
{
fileExtension = System.IO.Path.GetExtension(upldDocument.FileName);
}
else
{
//No file selected by user, which is why you can't get the extension.
// handle this eventuality here even if it means just returning from the function and not doing anything.
}
How are you checking the values? (in what event)
Did you set the enctype attribute of the form to "multipart/form-data" ?
in my current project I used a AsyncFileUpload control from AJAX Control Toolkits. After I got the async file upload part working, I needed to filter the file type so users can only upload image files. I found the following code off web and it worked well:
function uploadStarted(sender, args) {
var filename = args.get_fileName();
var filext = filename.substring(filename.lastIndexOf(".") + 1);
if (filext == "jpg" || filext == "jpeg" || filext == "gif" || filext == "bmp") {
return true;
}
else
{
// force uploading cancel
args.set_cancel(true);
// set reason of cancel
args.set_errorMessage("Invalid File Format Selected");
return false;
}
}
The problem is : I don't understand this javascript. What is the type of args parameter? Where are the methods such as "get_fileName()", "set_cancel()" defined? I went to the homepage of the AsyncFileUpload control but couldn't find any documentation regarding the "args".
Can someone help me out explaining this Javascript? Thanks
I think I can answer my own question
The first parameter identifies the object that fired the event, while the second provides information on the file being uploaded. In fact, it contains five useful properties accessed using the get_abc() syntax demonstrated above.
get_fileName() and get_path() both return the name of the file being uploaded
get_length() returns the size of the file in bytes once uploaded. Returns null prior to upload
get_contentType() returns the mime type of the file once it is uploaded. Returns null prior to upload
get_errorMessage() returns an error message should one occur. Returns null otherwise
For more details refer to this article:
http://p2p.wrox.com/content/blogs/danm/enter-asyncfileupload-control