如何将文件发布到远程网址?
我关注了有关将文件发布到远程网址的另一个问题: 上传带有 HTTPWebrequest (multipart/form-data) 的文件
它使我的 HttpHandler 中的远程 url 崩溃:“无法转换类型的对象‘System.String’来输入‘System.Web.HttpPostedFile’。”该方法是否发布了正确的文件数据,或者只是发布了一个字符串?
这是用于将文件发布到远程服务器的方法:
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;
}
}
这是远程服务器上的 HttpHandler:
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;
}
}
}
}
这是使用 HttpUploadFile 方法的方法:
var nvc = new NameValueCollection();
nvc.Add("user", userName);
nvc.Add("password", password);
nvc.Add("library", libraryName);
HttpUploadFile(destinationUrl, uploadFile, "file", "image/png", nvc);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
迭代
HttpFileCollection
将仅返回文件键。因此,您必须按如下方式更改 HTTP 处理程序:希望这会有所帮助。
Iterating through the
HttpFileCollection
will return only the file keys. So you have to change your HTTP handler as follow:Hope, this helps.