ASP.net - Multiple Upload with jQuery Multiple File Upload Plugin - asp.net

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.

Related

perform file upload without display upload control in ASP.NET

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

Upload file to ASP.Net Server without using FileUpload Control

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.

How do I retrieve HTML dynamically generated from an aspx page?

To be specific, here is what I am doing, and here is what I am trying to do:
I'm coding an ASP.NET page, with VB code behind. When the user clicks a button on the page, I send them an email with information and instructions. Rather than sending a plain text email, I send a nice, pretty, HTML-formatted one. Right now, I'm doing this in a way that I KNOW will be difficult to maintain. That is, I'm straight up writing out all of the html. i.e.
markup += "<fieldset>"
markup += "<legend>"
markup += "Required Documents"
markup += "</legend>"
...and so on. Is there a way to create an aspx page (with vb code behind), and send the html of that page in the body of the email? The information is dynamic, so this pseudo-page would need logic in the on-load event to format the html correctly.
Thanks!
WebClient client = new WebClient ();
string html = client.DownloadString("http://domain.com/emailtemplate.aspx?id=1");
If you have access to a database you can always drop the html in there otherwise, I solved this problem by creating a mailtemplate.html file with [replace] sections in it so all you have to do is read the file into a string object do your replaces and then send it out. If you have to you can maintain multiple templates this way. I use it mostly as a wrapper on emails my systems need to send out so my template has a [body] tag in it that gets replaced with whatever message I need to send. I have also used this method to wrap multiple files into a single email output.
I assume you want to build the html on the fly... One (certainly the most maintainable) solution is to build a template based system.
Technically you maintain your html (e.g. email shots) in a directory read the templates from your ASP.NET program, fill in the details and send the html mail to the user.

removing duplicate script from page

I am trying to make use of the yahoo exceptional performance rule : avoiding duplicate script
To do so i would like to be able to know whether or not a script was already added to the page before injecting it in the page. It looks like i can't figure what has been added in asp.net code behind unless i have a scriptmanager added to the page. but i would like to avoid using asp.net AJAX. From the description of the rule, it looks like it is something possible in php though.
Assuming that i can't do the check in my code behind, i was considering using jQuery $.getString function but it doesn't check before fetching the script. If i was to choose the javascript file, would i have to parse the whole http response in order to figure out which script was loaded on the page?
If the page is registering the scripts with the ASP.NET Page.ClientScript Register APIs then you can use Page.ClientScript.IsClientScriptIncludeRegistered. On the other hand, if you are using those APIs you don't really need to call it, since it already ensures only one of each is registered.
http://msdn.microsoft.com/en/us/library/system.web.ui.clientscriptmanager.isclientscriptincluderegistered.aspx
If the page just has regular ole script elements statically in the markup, and you need to detect if a script is loaded on the client side, you will have to get all the script elements on the page and look at their .src values. The thing with that is that some browsers automatically resolve that url to a full path, not just the one you declared. So, you can account for that in various ways -- you can just search for the end of the string being the script you want, or you can cause the url you want to compare with to also be resolved by setting it onto a dynamically created script element (which you never add to the DOM but is still resolved for you).
This is just off the top of my head, sorry if I get something wrong:
var s = document.createElement("script");
s.src = "foo.js";
var loaded, scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src === s.src) {
loaded = true;
break;
}
}
if (loaded) {
// this script is already loaded
// assuming you dont have multiple copies in different locations
}
You don't need to use any client-side scripting to do this... you can do this in your code behind using the ClientScriptManager without needing to make use of ASP.NET AJAX (I think you're confusing ClientScriptManager with ScriptManager*) in your control/page just use:
ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
or from your user controls:
Page.ClientScript.RegisterClientScriptInclude("some-script", "myScript.js");
This will use the key "some-script" & only register one copy of the script on the page.
*To be clear I think the confusion is arrising from the difference between these:
ClientScriptManager if a server-side helper class which is used to manage client side scripts (in other words its whole purpose is to do exactly what you are trying to do). It is accessed via the Page's ClientScript property.
ScriptManager is a Control used to aid client side Ajax scripting in ASP.NET AJAX
(hell I even confused myself & gave the wrong example code initially)
well that wouldn't actually work in a master detail scenario with multiple web user controls.
Then you wouldn't have control over who has to do the script initialization if the web user control is dynamic.
It's easier to link once, but a developer would have to weigh his options between ClientManager and using a script load.
yeah you have to parse the whole response...
why don't you create a javascript file and put all of your javascript there and then import that javascript file in your code??? in this way you can get rid of duplicate script insertion.

Large File uploading to asp.net MVC

I need a way to upload large files (600 mb to 4 gb) in an asp.net mvc website.
Currently I am using swfupload; it works well enough, but it is a huge hit on the webserver because it sends it in one big upload, plus I have to set it in the web.config to allow that huge of a file, which is a huge security risk. In the past when I was doing web forms development I used Neatupload which breaks up the file into chunks and uploads them individually. I am looking for a way to upload large files in mvc that uploads via chunking it up. Any ideas on how I could do this?
Silverlight File Upload
I ended up using Darren Johnstone's ASP.NET File Upload Module to handle the uploading on the server side. Though I modified it slightly so that it could take a guid on the querystring that it would save the temp file to that guid name.
It was nice because it saved the file as it arrived at the server, and stripped the file out of the posted data which it then sends to the action on the controller that was specified.
Example in my view:
<input id="FileGUID" name="FileGUID" type="hidden" value="f632c00b-9b66-4716-8075-79df63b780fb" />
<input type="file" id="FileUpload1" name="fileUpload1" />
<script type="text/javascript">
var UploadUrl = '/Video/AsyncUpload?FileGUID=f632c00b-9b66-4716-8075-79df63b780fb';
$(function() {
$("#FileUpload1").makeAsyncUploader({
upload_url: UploadUrl,
flash_url: '/Content/Flash/swfupload.swf',
button_image_url: '/Content/Images/blank-button.png',
button_text: '<font face="Helvetica, Arial" size="13pt" color="#ffffff">Upload File</font>',
disableDuringUpload: 'input[type="submit"]',
file_size_limit: '8024 MB',
button_text_top_padding: 2
});
});
</script>
Then in the actual save action for this page I look for a file where the asyncupload action would have saved the file based on the FileGUID
A SignalR implementation example can be found here.
This also includes functionality for working with HttpContext.Request.GetBufferlessInputStream(), which allows you to begin working with the post data before it's fully uploaded.

Resources