AJAX Toolkit - AsyncFileUpload Control Return Data - asp.net

I am using the AsyncFileUpload control provided by the Ajax Toolkit. I am needing to store the file uploaded in a temporary directory and then return the temporary file name back to the client (or set viewstate) so that on the next post back it can be committed to a database.
Does anyone have any ideas as the best approach to do this, if even possible?

Yes. It is possible.
OnClientUploadComplete is fired on the client-side after the upload has completed. Then just use get_fileName() to return the name of the file being uploaded.
Example:
function uploadCompleted(sender, args)
{
alert(args.get_fileName());
}

Related

Dynamic destination with AjaxFileUpload

I am using an AjaxFileUpload for multiple file upload. It is working, but I want to change the destination with the value in a textbox. The code is below which is in the AjaxFileUpload1_onUploadComplete method:
string myDir= myDirTextBox.Text.Trim();
AjaxFileUpload1.SaveAs(Server.MapPath("../allarticles/"+ myDir+"/"+e.FileName));
I debug the project and write a name in the myDirTextBox. Then when I click the Upload File button the value of this textbox is always null. That's why I can't change the destination dynamically.
I have read this article but it is not clear: upload multiple files with ajaxFileUpload with different file ids
What is the problem and how can I solve it?
When server event occurs the page goes through complete page lifecycle.
That means your code deals with new, uninitialized version of a page which is not related in any way with the page you see in a browser.
To save the value of a textbox and utilize it later you need to write some code to store this value between page requests. This can be simple JavaScript code attached to Upload button, that posts textbox value with AJAX to a server. Server, in turn, will store this value in session or another persistent storage.

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

Storing ascx in database

I would like to store the ascx control code into a database. Then rather then load the control from a filepath location, I would like to retrieve it from the database and load it into the UserControl. The UserControl.LoadControl only has two overload options. Without saving the control from a database to a temporary file and then load from the temporary file, is it possible do this direct from the database?
Can you use ParseControl instead? Link to MSDN.
The method accepts a string that is then compiled on the fly as a Control object.
You could load your control markup from the database and then hand it off to ParseControl to get an instance of your control back.
Hope this helps!
The only problem is that the ParseControl does not cause compilation, so if there are any Codes in your ascx, they will not get executed.
So far the only option for me has been to write the ascx to file (either permanently or temporarily) and then use LoadControl method to load the ascx.

ASP .NET PageMethods - File Upload

I am trying to create an ajaxy file upload.
Here is the asp code:
<input type="file" id="supportingDocs" runat="server"/>
<input type="button" id="uploadBtn" onclick="upload();" value="Upload"/>
Here is the javascript:
function upload()
{
PageMethods.uploadFile($get('supportingDocs').value, onSucceed, onFail);
}
Here is the relevant C# code:
[WebMethod]
[ScriptMethod]
public static string uploadFile(string files) {
HttpRequest request = HttpContext.Current.Request
........
}
What I am trying to get is the HttpFilesCollection from the request which is empty. I know that PageMethods do not follow the normal asp .net lifecycle. However looking at the HttpRequest object while stepping through the code in debugging I see that everything else in the request is there but the "Files" property is empty. I'm probably missing something here and this method of uploading files might not even be possible.
You could always just use the one provided by the AjaxControlToolkit, i.e. ASyncFileUpload
You could consider the jquery plugin: http://www.uploadify.com/
The file upload control works by sending a post request back to the server with the file contents. That is how the file upload is built. with that said, I'm not sure how the inner workings of all these file upload plugins operate, but out of the box even with ASP.NET AJAX services, it may be better to consider some other service.
If you wanted to use a service, you could try the Sys.Net.WebServiceProxy.invoke method, which gives you control over the post, serialize the form data to post to the server. Again, that's in theory, I'm not 100% sure how this all works through AJAX.
HTH.
If you want to upload a file without a full postback, try SWFUpload. It has a very nice file browser option and other features, unlike ASP.NET AJAX AsyncFileUpload which looks very limited.
SWFUpload demo: http://demo.swfupload.org
A popular jquery option is uploadify, see this stackoverflow post.
I never was able to get asynchronous file upload working without flash.
Update
This post claims that AsyncFileUpload doesn't use flash, so that may be an advantage over uploadify and SWFUpload.
Ok so I ended up using both the asp async upload and page methods.
The AsyncFileUpload worked well for actually saving the file on the server but I still needed to run some server-side code to write out the DB and also list the current files uploaded to the server. Unfortunately anything you change client-side will not get rendered since there is no post-back after the upload. So I just set the OnClientUploadComplete to a JS function that uses a page method.
ASP Code:
<asp:AsyncFileUpload ID="asyncFileUpload" runat="server" OnUploadedComplete="uploadFile" OnClientUploadComplete="showUploadedFiles" ThrobberID="uploading"/>
Javascript:
function showUploadedFiles()
{
PageMethods.getUploadedFiles(onSucceed, onFail);
}
function deleteDoc(docId)
{
PageMethods.deleteDocument(docId, onSucceed, onFail);
}
function onSucceed(result, userContext, methodName)
{
$get('uploadedFiles').innerHTML = result;
}
function onFail(error, userContext, methodName)
{
$get('uploadedFiles').innerHTML = "<p style='color: red;'>AJAX Error!</p>";
}

ASP.NET 2.0 PageComplete Event troubles and File downloading

I am trying to place an action to happen after an entire .aspx page displays. The "action" is a function that uses the Response object to send a file to the user.
More detailed information:
I am trying to replicate the behavior of a link on the page, from a sidebar. I.E. I have a link on the main page for the Export action, and it works fine -- since the page is already displayed before the user clicks it. But when the user is on a sidebar, clicks the link, it should take them back to this main page and then send the file after it displays.
I did some research and thought that using the PageComplete event would be well-suited for this, so I created my event handler and put the call to the export code (it keys off of a query string when loaded from the sidebar) inside my PageComplete event handler. But it behaves just the same way - the browser download box pops up and the page is never loaded before or after.
If it helps to understand what I'm doing here is a snippet of the code used to send the list to the user.
Response.Clear();
Response.BufferOutput = true;
Response.ContentType = "application/ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=MyList.xls");
Response.Write(listManager.ExportLists(mycode));
Response.End();
I would prefer a way to use a page event to load the page, rather than tinkering with this logic. But, if there is a clean and easier way to get the file sent, and it allows for loading the page then sending the file, that would be fine too.
Is there another Page event I can use besides PageComplete, or is it possible I am missing something?
EDIT: Sorry about the verbosity. I realize that I can't change the way HTTP requests work - I'm only looking for an acceptable solution that achieves more or less the same results. It seems like the way to go is to force a refresh of the page after a couple of seconds (thus ensuring that it loads before the file download code is executed) -- so I am looking for a way to do this as the first answer suggests - refresh to a download. (It doesn't have to be delayed either, if there's a way to refresh with no waiting)
Why doesn't this code work?
private void Page_LoadComplete(object sender, System.EventArgs e)
{
if (Request.QueryString["action"] != null)
{
if (Request.QueryString["action"] == "export")
{
Response.Redirect("MyHome.aspx?action=exportnow", false);
}
if (Request.QueryString["action"] == "exportnow")
{
ExportMasterList();
}
}
}
What it's supposed to do: after page loading is complete, do a Response.Redirect, reloading itself with a different query string. When it reaches the Page LoadComplete event again, the second time it will trigger the function which writes out the file.
What it actually does: Apparently repeats the same problem twice... it goes back to the same problem, how do you execute an action after the page loads, or wait until the page completely finishes loading, then trigger a refresh which will execute the action? Is there no way for ASP.NET to do something by itself without the user clicking on something?
If that's the case, then an auto-refresh after 2 seconds would also be acceptable... but I'm not sure how to do that.
The server can only return one object to the user, a file download or a page. The best you can manage is to return the user to a page that refreshes to a file download.

Resources