1

可以使用 FileUpload Control 和 WebMethod 上传文件吗?

我想避免 UpdatePanel 和 ScriptManagers。

我该怎么做?Web 方法将是什么样的参数?有什么例子吗?

谢谢!

4

1 回答 1

2

I could not find solution you asked using WebMethod so I come up with alternative solution which is using HTTPHandler or better known as ASPX control/page.

To achieve what you wanted, I use Valums File Upload, there are many alternative out there but this is the one that I found very suitable for my case. You can find more information, documentation and download the javascript code here:

http://valums.com/ajax-upload/

The code also give example of how to handle the request in server side however, it doesn't include code example in .net so I found this project.

http://www.codeproject.com/KB/aspnet/AspNetHandlerAjaxUpload.aspx

Which use Valums File Upload and handle the file upload request using .Net C# on server side.

To summarize, here is how you use the Valums File Upload on client side:

  1. Make sure reference the CSS and Javascript file downloaded from Valum File Upload website.
  2. Use this code for creating file upload control

    <div id="divFileUpload">
        <noscript>
            <p>
                Please enable JavaScript to use file uploader.</p>
        </noscript>
    </div>
    
  3. Use this javascript code to setup the file upload control

    $(function () {
        var uploader = new qq.FileUploader({
            element: document.getElementById('divFileUpload'),
            action: 'FileUpload.ashx',
            onComplete: function (id, fileName, responseJSON) {
                if (responseJSON.Success) {
                    alert("Success");
                }
            }
        });
    });
    

On the server side:

  1. Create ASHX file to handle request from the client side.
  2. Sample code

    public class FileUpload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //Save the file here
    
            //Return Json value to client
            context.Response.Write("{ \"Success\": true }");
        }
    }
    
  3. Very important, return JSON type to the client.

For more detail about how to handle the request from client side, please refer to the URL above.

All credits go to the Andrew Valums for the Valums File Upload and Syed BASHAR for the .Net server code using Valums File Upload.

于 2011-07-05T17:17:22.243 回答