How to post file to remote url?
I followed another question about posting a file to a remote url: Upload files with HTTPWebrequest (multipart/form-data)
It is making the remote url crash in my HttpHandler with: "Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'." Is the method posting the right file data, or is it posting just a string?
This is the method that is used to post the file to the remote server:
public void开发者_运维技巧 HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
Response.Write(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
var wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
var rs = wr.GetRequestStream();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
var stream2 = wresp.GetResponseStream();
var reader2 = new StreamReader(stream2);
Response.Write(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex)
{
Response.Write("Error uploading file: " + ex.Message);
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
This is the HttpHandler on the remote server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
namespace SitefinityWebApp.Widgets.Files
{
public class UploadFileHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//VALIDATE FILES IN REQUEST
if (context.Request.Files.Count > 0)
{
try
{
//HANDLE EACH FILE IN THE REQUEST
foreach (HttpPostedFile item in context.Request.Files)
{
item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName));
context.Response.Write("File uploaded");
}
}
catch (Exception ex)
{
//NO FILES IN REQUEST TO HANDLE
context.Response.Write("Error: " + ex.Message);
}
}
else
{
//NO FILES IN REQUEST TO HANDLE
context.Response.Write("No file uploaded");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
And this is how you use the HttpUploadFile method:
var nvc = new NameValueCollection();
nvc.Add("user", userName);
nvc.Add("password", password);
nvc.Add("library", libraryName);
HttpUploadFile(destinationUrl, uploadFile, "file", "image/png", nvc);
Iterating through the HttpFileCollection
will return only the file keys. So you have to change your HTTP handler as follow:
//HANDLE EACH FILE IN THE REQUEST
foreach (string key in context.Request.Files)
{
HttpPostedFile item = context.Request.Files[key];
item.SaveAs(context.Server.MapPath("~/Temp/" + item.FileName));
context.Response.Write("File uploaded");
}
Hope, this helps.
精彩评论