.NET WebMethod FileUpload

帅比萌擦擦* 提交于 2019-12-24 06:52:00

问题


is possible to upload a file by using FileUpload Control and WebMethod?

I would like to avoid the UpdatePanel and ScriptManagers.

How can I do it? What kind of parameter the Web Method would be? Is there any example?

Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/4155069/net-webmethod-fileupload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!