如何将文件发送到ASHX通用处理程序 [英] How to send file to ASHX generic handler

查看:89
本文介绍了如何将文件发送到ASHX通用处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2台服务器,它们之间没有连接,一台(A)有数据输入表格,我必须将这些数据移动到第二台服务器(B)。



我将(A)中的数据作为csv文件发送到服务器(b)中的处理程序。我使用以下代码发送数据,但文件未在处理程序中接收。 context.Request.Files.Count始终< 0.(Hanldler工作正常,我用文件上传器检查了相同的内容)。以下代码会出现什么问题?或任何其他转移数据的建议?



我尝试过:



I have 2 servers, there is no connection between them, one (A) has data input forms and I have to move this data to the second Server (B).

I am sending data from (A) as csv file to the handler in server(b). I used the following code to send data, but file is not receiving at the handler. context.Request.Files.Count is always < 0. (Hanldler is working fine, i have checked the same with a file uploader). what would be wrong in the below code? or any other suggestion to transfer data?

What I have tried:

const string FILE_PATH = "C:\\Docs\\SampleCV.csv";
    const string FILE_NAME = "SampleCV";
    string UPLOADER_URI = string.Format("http://GIC1493-DSK1:82/ExportData.ashx?FILE_NAME={0}", FILE_NAME);
    var httpRequest = WebRequest.Create(UPLOADER_URI) as HttpWebRequest;
    using (Stream stream = File.OpenRead(FILE_PATH))
    {
        httpRequest.Method = "POST";

        //stream.Seek(0, SeekOrigin.Begin);
        //stream.CopyTo(httpRequest.GetRequestStream());
        //var httpResponse = httpRequest.GetResponse();
        //StreamReader reader = new StreamReader(httpResponse.GetResponseStream());
        //var responseString = reader.ReadToEnd();
        //lblMsg.Text = "Posted to server";            

        Stream webStream = null;
        try
        {
            if (stream != null && stream.Length > 0)
            {
                long length = stream.Length;
                httpRequest.ContentLength = length;
                webStream = httpRequest.GetRequestStream();
                stream.CopyTo(webStream);
            }
        }
        finally
        {
            if (null != webStream)
            {
                stream.Flush();
                stream.Close();
                webStream.Flush();
                webStream.Close();
            }
        }
        using (HttpWebResponse response = HttpWebResponse)httpRequest.GetResponse())
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            var responseString = reader.ReadToEnd();
            lblMsg.Text = "Posted to server. Response is : " + responseString; ;
        }

推荐答案

您的处理程序正在等待mpartpart/formdata [ ^ ]请求,但您的代码只是发送文件的原始字节。



您需要构建一个正确的请求来传输文件:

Your handler is expecting a multipart/formdata[^] request, but your code is simply sending the raw bytes of the file.

You need to build a proper request to transmit the file:
public static class Extensions
{
    public static void PrepareFileUpload(this WebRequest request, string fieldName, Stream fileStream, string fileName, string contentType)
    {
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        request.Method = "POST";
        
        using (var stream = request.GetRequestStream())
        using (var writer = new StreamWriter(stream, System.Text.Encoding.ASCII))
        {
            writer.WriteLine();
            writer.WriteLine("--{0}", boundary);
            writer.WriteLine("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", fieldName, fileName);
            writer.WriteLine("Content-Type: {0}", contentType);
            writer.WriteLine();
            writer.Flush();
            
            fileStream.CopyTo(stream);
            
            writer.WriteLine();
            writer.WriteLine("--{0}--", boundary);
        }
    }
}

...

var httpRequest = WebRequest.Create(UPLOADER_URI);
httpRequest.PrepareFileUpload("fieldName", stream, "MyFile.csv", "text/csv");

using (var response = httpRequest.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
    var responseString = reader.ReadToEnd();
    lblMsg.Text = "Posted to server. Response is : " + responseString;
} 





或者,如果你总是上传存储在服务器A的文件系统上的文件,你可以使用 WebClient类 [ ^ ]:



Alternatively, if you're always uploading a file stored on server A's file system, you can use the WebClient class[^]:

using (var client = new WebClient())
{
    byte[] response = client.UploadFile(UPLOADER_URI, FILE_PATH);
    string responseString = Encoding.UTF8.GetString(response);
    lblMsg.Text = "Posted to server. Response is : " + responseString;
}





或者,如果您使用的是.NET 4.0或更高版本,则可以使用 HttpClient类 [ ^ ]:



Or, if you're using .NET 4.0 or higher, you can use the HttpClient class[^]:

private static readonly HttpClient Client = new HttpClient();
...
using (var content = new MultipartFormDataContent())
{
    content.Add(new StreamContent(stream), "fieldName", "MyFile.csv");
    
    using (var response = await Client.PostAsync(UPLOADER_URI, content))
    {
        response.EnsureSuccessStatusCode();
        string responseString = await response.Content.ReadAsStringAsync();
        lblMsg.Text = "Posted to server. Response is : " + responseString;
    }
}



注意:你需要让你的代码 async 使用它。


NB: You'll need to make your code async to use this.


这篇关于如何将文件发送到ASHX通用处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆