In my ongoing efforts to learn asp.net, I recently read about web handlers. Hmmm … seems like a convenient way to handle file upload from a Flex app. Although I’m much more comfortable with PHP, I hacked something together that worked okay on my server (.NET 2.0). I suspect others have blogged about this, but another example never hurts and I tried to distill this one down to a very simple level. Hopefully, it will be easy for other asp.net beginners to pick up on and expand.
There are some hacks in the .ashx file, including hardcoding the physical location of the upload folder on my server (which no longer exists after testing). I believe there is a more elegant way to specify the upload folder in the web.config file and then access it in the script using WebConfigurationManager.AppSettings. Haven’t had time to try that.
If you’re an experienced .NET pro, go ahead and laugh (although suggestions on making the process better are quite welcome). Beginners are welcome to download the files here (MXML and Uploader.ashx). It may go without saying, but make sure you have write access on the upload folder 🙂
Hello!
Last week, I’ve also created the upload program with using ASP .NET to accept uploaded file via Flex.
(Mine does not store the data in filesystem but in DataBase.)
But I didn’t the way to use Web Handler so that I wrote the code in the normal aspx, which has no HTML tag.
I think your is more excellent than mine, and I’m going to change my code to Web Hander’s one.
Thank you for your time and posting this!
By the way, you can define upload folder in web.config liken this:
<add key=”uploadDir” value=”D:\\Domains\\algorithmist.net\\
And you can retrievet the parameter like this:
string uploadDir:
uploadDir = System.Configuration.ConfigurationSettings.AppSettings[“uploadDir”];
Thanks for the info. I will go back and add that step. I just ran out of time 🙂
cool, your script completes my collection. Here’s the VB version I found:
dim myFile as HttpPostedFile=Request.Files(0)
myFile.SaveAs(Server.MapPath(myFile.FileName))
http://shang-liang.com/blog/flash-upload-file-with-aspnet/
Doesn’t work
still have an error
Error #2044: Unhandled IOErrorEvent:. text=Error #2038: File I/O Error.
don’t no how to solve it
An I/O error is most likely an incorrect path to the upload folder or the result of not having write access to that folder. it works fine for me (as well as many others).
How can i pass an parameter to my webserver ashx ?
Path to upload folder will be different.
can somebody help me ?
ashx handler can accept GET and POST parameters just like a regular page. Just write the query string in the url (MyHandler.ashx?param=value) and read them on the server with Request.QueryString[“param”]
Thank a lot Benyamin Shoham !
It works !
Hi..!
Thanks a lot for such a great post
Now I am able to upload file in server from Flex.
But still I am not able to upload file having size of 4MB or more.
Any suggestion,Please help…
My Flex application take a snapshot from a video playback and upload the snapshot to server.
My question is how can I upload a binary data(the jpeg file) to your Uploader.ashx
var iBytesA:ByteArray = imgEncoder.encode(imgData);
The iBytesA is the binary data that I need to upload to server.
Thanks for sharing. I appreciate it!
How can I set the upload directory to a local-to-the-site directory?
like uploadDir = “~/uploads/”
or uploadDir = “./uploads/”
it would seem to be something like that, but cant get it to work.
Any help would be appreciated.
ps. if there is a multiple file uploader similar to these, would some post, or like?
I am also not able to upload anything large.
I have tried the addition to the webconfig:
but doesnt seem to take effect.
Anyone?
Hi,
Very nice post. Expecting more from you.
Regards,
Dharma
Hi,
nice post.
I’m having a few probs. Perhaps somebody can help. I have copied an asp.net aspx file in order to get my files up to the server. But the events that are dispatched is when I test the aspx are only the IOerror 2038# and the openEEvent that stuck on phase=2. Here is the script:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace FlashUpload
{
//[ToolboxData(“”)]
//[PersistChildren(true), ParseChildren(true), Designer(typeof(FlashUpload))]
public class FlashUpload : Control
{
private const string FLASH_SWF = “test.swf”;
[Category(“Behavior”)]
[Description(“The page to upload files to.”)]
[DefaultValue(“”)]
public string UploadPage
{
get
{
object o = ViewState[“UploadPage”];
if (o == null)
return “”;
return o.ToString();
}
set { ViewState[“UploadPage”] = value; }
}
[Category(“Behavior”)]
[Description(“Query Parameters to pass to the Upload Page.”)]
[DefaultValue(“”)]
public string QueryParameters
{
get
{
object o = ViewState[“QueryParameters”];
if (o == null)
return “”;
return o.ToString();
}
set { ViewState[“QueryParameters”] = value; }
}
[Category(“Behavior”)]
[Description(“Javascript function to call when all files are uploaded.”)]
[DefaultValue(“”)]
public string OnUploadComplete
{
get
{
object o = ViewState[“OnUploadComplete”];
if (o == null)
return “”;
return o.ToString();
}
set { ViewState[“OnUploadComplete”] = value; }
}
[Category(“Behavior”)]
[Description(“The maximum file size that can be uploaded, in bytes (0 for no limit).”)]
public decimal UploadFileSizeLimit
{
get
{
object o = ViewState[“UploadFileSizeLimit”];
if (o == null)
return 0;
return (decimal)o;
}
set { ViewState[“UploadFileSizeLimit”] = value; }
}
[Category(“Behavior”)]
[Description(“The total number of bytes that can be uploaded (0 for no limit).”)]
public decimal TotalUploadSizeLimit
{
get
{
object o = ViewState[“TotalUploadSizeLimit”];
if (o == null)
return 0;
return (decimal)o;
}
set { ViewState[“TotalUploadSizeLimit”] = value; }
}
[Category(“Behavior”)]
[Description(“The description of file types that you want uploads restricted to (ex. Images (*.JPG;*.JPEG;*.JPE;*.GIF;*.PNG;))”)]
[DefaultValue(“”)]
public string FileTypeDescription
{
get
{
object o = ViewState[“FileTypeDescription”];
if (o == null)
return “”;
return o.ToString();
}
set { ViewState[“FileTypeDescription”] = value; }
}
[Category(“Behavior”)]
[Description(“The file types to restrict uploads to (ex. *.jpg; *.jpeg; *.jpe; *.gif; *.png;)”)]
[DefaultValue(“”)]
public string FileTypes
{
get
{
object o = ViewState[“FileTypes”];
if (o == null)
return “”;
return o.ToString();
}
set { ViewState[“FileTypes”] = value; }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Page.Form.Enctype = “multipart/form-data”;
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
string url = Page.ClientScript.GetWebResourceUrl(this.GetType(), FLASH_SWF);
string obj = string.Format(“” +
“” +
“” +
“” +
“” +
“” +
“” +
“”,
url,
ResolveUrl(UploadPage),
HttpContext.Current.Server.UrlEncode(QueryParameters),
string.IsNullOrEmpty(OnUploadComplete) ? “” : “&completeFunction=” + OnUploadComplete,
string.IsNullOrEmpty(FileTypes) ? “” : “&fileTypes=” + HttpContext.Current.Server.UrlEncode(FileTypes),
string.IsNullOrEmpty(FileTypeDescription) ? “” : “&fileTypeDescription=” + HttpContext.Current.Server.UrlEncode(FileTypeDescription),
TotalUploadSizeLimit > 0 ? “&totalUploadSize=” + TotalUploadSizeLimit : “”,
UploadFileSizeLimit > 0 ? “&fileSizeLimit=” + UploadFileSizeLimit : “”
);
writer.Write(obj);
}
}
}
I’ve tried also an another one, here:(thats the .ashx)
”’
”’ This handler takes a posted file and saves it to the disk.
”’
”’
Public Class MyHandler
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Try
‘System.Threading.Thread.Sleep(5000) ‘Slow down for testing only!
Dim myFile As HttpPostedFile = context.Request.Files(0)
Dim RootPath As String = “http://localhost/pics/”
If System.IO.File.Exists(context.Server.MapPath(RootPath & myFile.FileName)) Then
If CBool(context.Request.QueryString(“Overwrite”)) Then
myFile.SaveAs(context.Server.MapPath(RootPath & myFile.FileName))
Else
context.Response.Write(“500”) ‘File already exists and will not be overwritten.
End If
Else : myFile.SaveAs(context.Server.MapPath(RootPath & myFile.FileName))
End If
context.Response.Write(“200”) ‘IMPORTANT! Respond Ok.
Catch ex As Exception
context.Response.Write(“500”) ‘IMPORTANT! Respond not Ok.
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
but here I get only the openevent that stucks again at phase=2.
Can u please tell me what am I doing wrong and how to fix it. Perhaps should I do something with the web.config? but what?
any help would be greatfull,
thanks a lot.
jimmi