How to handle a file in ASP.net, that was uploaded from desktop application?
I am using WebClient.UploadFile
to upload a file to this kind of URL - http://example.com/file.aspx via HTTP POST method.
How can I get that file and save it to a sepecific location on the server? What code should I write inside file.aspx to do this?
When I search, all examples assume I use the file uplo开发者_运维知识库ad control. But how can I get and save a file sent via HTTP POST generally in ASP.Net?
I am using C#, so C# code example will be great. But I have no probs converting VB to C#.
In the server-side page (which, BTW, ought to be an ASHX rather than an ASPX), use the Request.Files
collection.
For example, you can write Request.Files[0].SaveAs(Server.MapPath("~/Something"))
I believe you should find this MSDN article suitable to your needs. WebClient.UploadFile Method You can see how the page_load is used to handle the file that is embedded in the http request from thew webclient
void Page_Load(object sender, EventArgs e) {
foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
}
}
After reviewing comment from @SLaks I would agree that using a .ashx would be a 'better' result. The code should look something like:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
foreach(string f in context.Request.Files.AllKeys)
{
HttpPostedFile file = context.Request.Files[f];
file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
// alternatively:
file.SaveAs(Path.Combine(Server.MapPath(@"\StorageFolder\",file.FileName);
//thanks @SLaks.
}
}
}
精彩评论