I'm developing an ASP.NET web app using VS2010,C#, I want to display a file upload control when my users click on a hyperlink (or label, it doesn't differ), and then the upload operation should be performed, I have no problem working with upload control, but currently I have an invisible upload control which display it using JavaScript in my hyperlink onclick function, the upload control is displayed but I don't know how the get the uploaded file, how should I perform this operation? I want to display upload file dialog when my users click on a label or hyperlink, then they can select their file and the file should be uploaded, and finally I should be able to work with this file in server side (I'm going to get file stream and store it in SQL), what are my options? JQuery? Ajax? JavaScript? or something else?
my JavaScript function:
function OpenFile()
{
document.getElementById("<%=fu.ClientID%>").style.display="";
var result = document.getElementById("<%=fu.ClientID%>").click();
document.getElementById("<%=fu.ClientID%>").style.display="none";
return false;
}
and my markup:
<asp:FileUpload ..... style="display:none;"....>
<ASP:hyperlink onclick="OpenFile();"...../>
After you select a file and do a PostBack, you can access the file as follows
<asp:FileUpload ID="FileUpload1" ..... style="display:none;"....>
Access the underlying posted file using the PostedFile
var fileLen = FileUpload1.PostedFile.ContentLength;
Byte[] Input = new Byte[fileLen];
myStream = FileUpload1.FileContent;
myStream.Read(Input, 0, fileLen);
Or just save it on the server:
FileUpload1.SaveAs(savePath);
I would like to recommend uploadify, it is built with flash. Very simple and easy to use with jQuery and asp.net.
Demo relies php for uploading, though it can be used with any platform including asp.net.
You have to write a handler file to do the uploading, streaming and sql storage part.
Check these answers
by #Zitun https://stackoverflow.com/a/4972872/206766
by #Blankasaurus https://stackoverflow.com/a/2501069/206766
Related
I have an ASP.NET web form to get name, email address and uploaded filename(s). Added an AjaxFileupload control (ASP.NET AJAX Toolkit v16.1 not to be confused with AsyncFileupload or ASP.NET FileUpload control) that works OK because it lets you upload files without doing any Postback at all avoiding to submit the same form more than one time (See sample here: Upload files and images without page PostBack / Refresh / Reload in ASP.Net - )
The control works fine, it saves the files but the problem is: once the fields in the form are validated, the file(s) are uploaded and I'm finally ready to Submit the form I can't get the path of the uploaded files because the AjaxFileUpload control doesn't have any method to do that :(
In other words you can't simply invoke AjaxFileUpload.GetListOfUploadedFiles() and get an ArrayList of uploaded files. I want to save all the fields on a record, name, email and all the filenames that this user has been uploaded so I can use this data to make a report.
Protected Sub OnUploadComplete(sender As Object, e As AjaxFileUploadEventArgs)
Dim fileName As String = Path.GetFileName(e.FileName)
Me.AjaxFileUpload1.SaveAs(Server.MapPath("/output/" & fileName))
End Sub
I've tried to catch the filenames there but once one file gets saved and you left the Sub the data is gone, so here is my question:
How can I do to get a String with all the files listed on the "uploaded files" section of the AjaxFileUpload control so when I Submit the form I can get all those filenames?
I've seen something related to that using Javascrit to change behaviour on queued files here: AjaxFileUpload automatically upload file once selected perhaps there is something like "Sys.Extended.UI.AjaxFileUpload.prototype._QueuedFiles" that I can use to get the filename list at the time of submitting the form.
Thanks!
PS: Save the binaries on the DB is out of the question because it means a hugue increase on database size since there will be several users each one uploading files about 6Mb each thus increasing DB size.
How can I add a file browse functionality on my asp.net web form ?
I have a similar button in my winforms app and now I need it on asp.net my web page.
FileUpload control is used to select and post file to a web server, I just need to select file path/name without sending file.
Should I add some JS to delete FORM item before doing POST or any other simplier solution exists ?
Follow this.
You can use asp:FileUpload , when user selects a file, you need to get that path using this - document.getElementById("fileeupload_id").value. Save this value to hidden field , say with id hdn.
Reset file selection using this - document.getElementById("fileeupload_id").value = "".
So that, when page will be posted, you file will not be posted,rather filename will be posted as hdn.Use Request.Form["hdn"] to get selected file path.
In my ASP.Net website I want to upload a file onClickEvent of LinkButton. I dont have a space to show a FileUpload Control. But if we use fileUpload control it is easy to upload a file using:
String filename = Path.GetFileName(FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/files/") + filename);
How do I open file browser on onClick event of LinkButton and save my file inside the Files folder present on the server?
EDIT:
can we use "OpenFileDialog" From Windows.Forms? If yes, how? i am just asking...
You can use javascript as suggested by Neil Thompson. However, my preferred solution to this issue is the CSS method as described in this post. You can also use the ASP upload control if you wish, and it will be hidden in the same way, allowing you to handle the file in the code behind as you usually would.
Also, as far as I can tell this works in all popular browsers.
I am creating FileUpload controls at run time. When I click a LinkButton a new FileUpload control is generated.
Now suppose I have selected a file from a FileUpload control and I click the LinkButton. The previous FileUpload control loses its path. However, I'm maintaining the ViewState of each control that I create at runtime by using this line:
f1.enableviewstate = true;
How do I maintain the selected file for a FileUpload control?
Steps
user selects a file
user click LinkButton (issues a postback that adds additional file uploading control)
server side should get the file on postback and store it somewhere (anywhere)
replace first <input type=file> with something like Label and check mark icon (to tell user the file has already been uploaded (or even a read-only text box with disabled browse button to fake file upload control - however you won't be able to display correct file path in it)
user is presented with a new form that has new empty file upload control in showing already uploaded files.
For security reasons you can't manipulate <input type=file> in any way shape or form.
Hack approach
If I understood you correctly your link button adds additional file upload controls to your page. Instead I'd create a sufficient number of upload controls the first time and display just one. Others would be hidden by CSS. After user clicks the LinkButton, it would however have only client-side Javascript functionality that would reveal additional control. And another... and another... and another... until maximum is reached.
Complex approach
You could however make it in a different way by using more Javascript and make it more Web 2.0-ish. You should however upload those files via <iframe>
as some of the others mentioned, you cannot preserve the viewstate of a FileUpload due to security issues.
What you could do is to simply add a Label just below the FileUpload. When the user clicks on the linkbutton in order to generate a new FileUpload, a postback will be fired where you could check whether the FileUpload controls present on the page have some value (i.e. the user already selected a file to upload), and if so, you could directly start to upload that file and show the result (the path or filename) on the label, just that the user knows he has added that file already. You could also hide the fileupload and additionally add a remove link to again remove the uploaded file (similar approach as Gmail does).
Hope this helped.
Juri
You can't pre-select a file path in the file upload input tag (security related - the user must select the file), so .Net is not able to populate the value from viewstate.
Consider if you really need to at it at runtime?
If you really need to at runtime; Don't forget to add it to the closest container's Controls property. Doing this makes sure it's state is serialized to the ViewState.
Hope this helps...
as per me there is no way to persist viewstate of fileupload in asps.net.
u can store it's value in hidden field,session etc file u can not be able to assign that value to again file upload because it is read only
I know how to upload with ASP.net's FileUpload control.
What I want to do is use this jQuery Multiple File Upload Plugin to upload multiple files.
Here is exactly what it does when multiple files are selected for upload:
<input type="file class="multi MultiFile" id="MultiFile1_F3" name="file1[]" style="position: absolute; top: -3000px;">
But I cannot figure out how to manipulate these files from asp.net.
I have tried using Request.Files as the following link instructs:
ASP.Net Upload of multiple files after choosing them from jQuery
That doesn't work. I think that only works for controls marked with runat="server" at compile time.
Does anyone know how to do this? Maybe something in Request.Form...?
Thanks for your help!
Two things to check:
Make sure your form has the enctype="multipart/form-data" attribute set. This is required to enable uploads.
Make sure all file inputs have both id and name attributes set. For some reason, if you don't set both, wierd things happen.
Also, runat="server" shouldn't have anything to do with whether Request.Files works or not -- this is more an issue of the browser actually posting the files.
This jQuery plugin was giving every generated input control the exact same name attribute.
For this reason, the files were not posting.
I built my own javascript solution.
I will post a link to the code in a comment.
Edit
I revisited this and found that what I was trying to do wasn't very difficult at all. I got the the jquery multiple file upload plugin to work fine with my aspx form. I don't know why I was having so much trouble before.
1.) Include the jQuery library on the web form:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" />
2.) Reference the multiple file plugin on the web form (Download it here):
<script src="jquery.MultiFile.pack.js" type="text/javascript">
3.) Add a file input on your web form with class="multi":
<input type="file" class="multi" />
4.) Execute some code or call a method like this on form submission:
void SendMail(string from, string to, string subject, string body, string smtpServer)
{
// create mail message
MailMessage mail = new MailMessage(from, to, subject, body);
// attach posted files
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile file = Request.Files[i];
mail.Attachments.Add(new Attachment(file.InputStream, file.FileName));
}
//send email
new SmtpClient(smtpServer).Send(mail);
}
This is all that I had to do to attach multiple files to an email sent from an aspx page.
If you want to increase the total size of the files that can be uploaded, add this to your web.config file:
<system.web>
<httpRuntime executionTimeout="240" maxRequestLength="30720"/>
</system.web>
The executionTimeout is measured in seconds and maxRequestLength is measured in kilobytes. In this example, the request will timeout after 4 minutes and will allow a 30mb request.
It's been a bit since I did that kind of thing in .NET, but once you begin cloning form inputs dynamically, I think you have to go out to Request.Form and find the submitted values manually. I wrote up the jQuery code to clone some (non-file) inputs with sequential identifiers here. As long as you have unique identifiers, you can run a loop to see if Request.Form["MultiFile1_F" + counter] exists and go from there.
I highly recommend Uploadify as a mulitple file uploader. It uses jquery and flash to allow the user to upload multiple files at once through ctrl + clicking on all desired files. It then displays a queue of the files uploading and removes the file from the queue on completion. It also allows you to specify which extension to allow the user to upload as well which prevents you from having to do extension validation.
EDIT:
If you dont want to use flash Ajax Upload works really well too. If users on my site company's site dont have the right version of flash that works best with uploadify, I switch to Ajax Upload. They both work very well for me.