问题
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:
- Make sure reference the CSS and Javascript file downloaded from Valum File Upload website.
Use this code for creating file upload control
<div id="divFileUpload"> <noscript> <p> Please enable JavaScript to use file uploader.</p> </noscript> </div>
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:
- Create ASHX file to handle request from the client side.
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 }"); } }
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