Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在c中使用HTTP POST发送文件#_C#_File_Web Applications_Http Post - Fatal编程技术网

C# 在c中使用HTTP POST发送文件#

C# 在c中使用HTTP POST发送文件#,c#,file,web-applications,http-post,C#,File,Web Applications,Http Post,我有一个小型的C#web应用程序。如何获得允许用户通过HTTP POST发送文件的C#代码。它应该能够发送文本文件、图像文件、excel、csv、文档(所有类型的文件),而无需使用stream reader和all。您可以尝试以下代码: public void PostMultipleFiles(string url, string[] files) { string boundary = "----------------------------" + DateTime.Now

我有一个小型的C#web应用程序。如何获得允许用户通过HTTP POST发送文件的C#代码。它应该能够发送文本文件、图像文件、excel、csv、文档(所有类型的文件),而无需使用stream reader和all。

您可以尝试以下代码:

    public void PostMultipleFiles(string url, string[] files)
{
    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";
    httpWebRequest.KeepAlive = true;
    httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
    Stream memStream = new System.IO.MemoryStream();
    byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary     +"\r\n");
    string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition:  form-data; name=\"{0}\";\r\n\r\n{1}";
    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    for (int i = 0; i < files.Length; i++)
    {
        string header = string.Format(headerTemplate, "file" + i, files[i]);
        //string header = string.Format(headerTemplate, "uplTheFile", files[i]);
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
        memStream.Write(headerbytes, 0, headerbytes.Length);
        FileStream fileStream = new FileStream(files[i], FileMode.Open,
        FileAccess.Read);
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        memStream.Write(boundarybytes, 0, boundarybytes.Length);
        fileStream.Close();
    }
    httpWebRequest.ContentLength = memStream.Length;
    Stream requestStream = httpWebRequest.GetRequestStream();
    memStream.Position = 0;
    byte[] tempBuffer = new byte[memStream.Length];
    memStream.Read(tempBuffer, 0, tempBuffer.Length);
    memStream.Close();
    requestStream.Write(tempBuffer, 0, tempBuffer.Length);
    requestStream.Close();
    try
    {
        WebResponse webResponse = httpWebRequest.GetResponse();
        Stream stream = webResponse.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string var = reader.ReadToEnd();

    }
    catch (Exception ex)
    {
        response.InnerHtml = ex.Message;
    }
    httpWebRequest = null;
}
public void PostMultipleFiles(字符串url,字符串[]文件)
{
字符串边界=“------------------------------------”+DateTime.Now.Ticks.ToString(“x”);
HttpWebRequest HttpWebRequest=(HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType=“多部分/表单数据;边界=“+boundary;
httpWebRequest.Method=“POST”;
httpWebRequest.KeepAlive=true;
httpWebRequest.Credentials=System.Net.CredentialCache.DefaultCredentials;
Stream memStream=new System.IO.MemoryStream();
byte[]boundarybytes=System.Text.Encoding.ASCII.GetBytes(“\r\n--”+boundary+”\r\n”);
字符串formdataTemplate=“\r\n--“+boundary+”\r\n内容处理:表单数据;名称=\“{0}\”;\r\n\r\n{1}”;
string headerTemplate=“内容处置:表单数据;名称=\”{0}\“文件名=\”{1}\“\r\n内容类型:应用程序/八位字节流\r\n\r\n”;
memStream.Write(boundarybytes,0,boundarybytes.Length);
for(int i=0;i
试试这个

string fileToUpload = @"c:\user\test.txt";
string url = "http://example.com/upload";
using (var client = new WebClient())
{
byte[] result = client.UploadFile(url, fileToUpload);
string responseAsString = Encoding.Default.GetString(result);
}
使用.NET4.5(或者通过从NuGet添加包来使用.NET4.0)可以更容易地模拟表单请求。以下是一个例子:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}

我尝试过不同的方法,但没有一种对我有帮助。
如果您展示了一些您尝试过的方法,我们可能会看到它们有什么问题。现在,很难进行建设性的讨论。重复的和各种其他的。展示你所尝试的,和选民,请考虑是否一个问题,你是投票赞成是一个欢迎添加到网站或只是一个副本。只要倾倒50行代码不是一个答案。这个问题有很多答案,其中许多代码(也有更多的防错代码)已经内置在.NET类型中,比如WebClient和HttpClient。你能解释一下从receiver页面的检索过程吗?你能给出一个url示例吗。。是否包含文件名?是否必须始终使用多部分表单数据?