开发者

ASP.NET - uploading files to server - jQuery vs. .NET classes

I want to add to a server the ability to recieve uploaded files (eventually this server will copy the uploaded file to another location on the network).

I searched online and ran into jQuery for开发者_开发问答 ASP.NET. I just don't understand what's the use in it and how is it better. Why not using the usual .NET C# classes and functions, such as FileUpload.SaveAs and then copy the file? Am I missing something here?

Thanks.


jQuery is a client-side JavaScript library. it makes it easier to deal with the DOM. you CAN use it with asp.net, but it is NOT a part of it. As with all things, you should use the right tool for the job. if you are wanting to upload some files, then by all means use the asp.net file uploader. if you want some cutting-edge client-side effect then you should (probably) use jQuery.


You're going to run into issues trying to upload files purely with JavaScript. The XMLHttpRequest object (or its equivalent in the various browsers) does not serialize files (not sure how it could), so you have to resort to some "hacks" like submitting to an <iframe /> or using Flash. Neither are all that much fun.


If security is not a concern then you could created an Upload.aspx Page in your solution, which would look like.

protected void Page_Load(object sender, EventArgs e)
{
    foreach(var fileKey in Context.Request.Files.AllKeys)
    {
        try
        {
            var file = Context.Request.Files[fileKey];

            string serverRelativeLocation = "~/Images/";
            string saveLocation = Server.MapPath(serverRelativeLocation) + file.FileName;
            file.SaveAs(saveLocation); // This could also be a UNC Path as well.

            Context.Response.Write(string.Format("File {0} was uploaded Successfully.", file.FileName));
        }

        catch (Exception ex)
        {
            Context.Response.Write(ex.Message);
        }
    }

and on the client side, you can initiate the upload as follows:

public string UploadImage(string path)
{
    using (var myWebClient = new WebClient())
    {
        var responseArray = myWebClient.UploadFile("http://<<server>>/upload.aspx", "POST", path);
        return System.Text.Encoding.ASCII.GetString(responseArray);
    }
}


Firstly, I should note this:

  1. Standard .NET FileUpload control doesn't support partial page update. So you can't add it to the Updatepanel.
  2. AJAX file uploader has not much functionality on the client.

So sometimes you may try to use some custom jquery file uploaders (may be for validation or partial upload). And at this time jquery can help you. But from the server side, it will be still the same - bit arrays you deal with using .NET classes.

Jquery is always for the client side.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜