将图像和变量放在HTTP Post中(不使用FileUpload Control)

时间:2009-09-15 08:17:55

标签: c# asp.net

从我的帖子开始......

Saving an image from HTTP POST (Not using FileUpload Control)。我有点假设我可以使用Request.Files ..

为了测试保存功能,我现在正在查看通过HTTP Post发送图像,方法是在后面的代码中动态制作此HTTP Post并不使用FileUpload Control

这里有人感动..

Send a file via HTTP POST with C#

但是,我正在寻找一个更完整的样本,并确保维护其他POST变量。

事实上这个可能有帮助......

Multipart forms from C# client

更新: 对不起..问题是......

如何通过HTTP Post(没有文件上传控制)和其他POST变量将图像发送到网址,并让Request.Files在目标网址上提取它?

最后我使用WebHelpers类解决了它

Multipart forms from C# client

3 个答案:

答案 0 :(得分:1)

我使用以下代码:

<强>用法

List<IPostDataField> Fields = new List<IPostDataField>();
Fields.Add(new PostDataField() { Name="nameOfTheField", Value="value" }); //simple field
Fields.Add(new PostDataFile() { Name="nameOfTheField", FileName="something.ext", Content = byte[], Type = "mimetype" });

string response = WebrequestManager.PostMultipartRequest(
    new PostDataEntities.PostData()
    {
        Fields = Fields
    }
    ,
            "url");

<强> PostMultiPartRequest

    public static string PostMultipartRequest(PostData postData, string relativeUrl, IUserCredential userCredential)
    {
        string returnXmlString = "";

        try
        {
            //Initialisatie request
            WebRequest webRequest = HttpWebRequest.Create(string.Format(Settings.Default.Api_baseurl, relativeUrl));
            //Credentials
            NetworkCredential apiCredentials = userCredential.NetworkCredentials;
            webRequest.Credentials = apiCredentials;
            webRequest.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(apiCredentials.UserName + ":" + apiCredentials.Password)));
            //Post!
            webRequest.Method = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=";

            //Post
            //byte[] bytesToWrite = UTF8Encoding.UTF8.GetBytes(multipartData);
            string boundary = "";
            byte[] data = postData.Export(out boundary);
            webRequest.ContentType += boundary;
            webRequest.ContentLength = data.Length;
            using (Stream xmlStream = webRequest.GetRequestStream())
            {
                xmlStream.Write(data, 0, data.Length);
            }

            //webRequest.ContentType = "application/x-www-form-urlencoded";
            using (WebResponse response = webRequest.GetResponse())
            {
                // Display the status
                // requestStatus = ((HttpWebResponse)response).StatusDescription;

                //Plaats 'response' in stream
                using (Stream xmlResponseStream = response.GetResponseStream())
                {
                    //Gebruik streamreader om stream uit te lezen en om te zetten naar string
                    using (StreamReader reader = new StreamReader(xmlResponseStream))
                    {
                        returnXmlString = reader.ReadToEnd();
                    }
                }
            }
        }
        catch (WebException wexc)
        {
            switch (wexc.Status)
            {
                case WebExceptionStatus.Success:
                case WebExceptionStatus.ProtocolError:
                    log.Debug("bla", wexc);
                    break;
                default:
                    log.Warn("bla", wexc);
                    break;
            }
        }
        catch (Exception exc)
        {
            log.Error("bla");
        }

        return returnXmlString;

    }

<强> IPostdataField

public interface IPostDataField
{
   byte[] Export();
}

<强> PostDataField

public class PostDataField : IPostDataField
{
    public string Name { get; set; }
    public string Value { get; set; }

    #region IPostDataField Members

    public byte[] Export()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(stream);
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", Name));
                sb.AppendLine();
                sb.AppendLine(Value);
                sw.Write(sb.ToString());
                sw.Flush();
            }

            stream.Position = 0;

            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)buffer.Length);
            return buffer;
        }
    }

    #endregion
}

<强> PostDataFile

public class PostDataFile : IPostDataField
{
    public Byte[] Content { get; set; }
    public string Name { get; set; }
    public string FileName { get; set; }
    public string Type { get; set; } // mime type

    public byte[] Export()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            StreamWriter sw = new StreamWriter(stream);

            StringBuilder sb = new StringBuilder();
            sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"", Name, FileName));
            sb.AppendLine("Content-Type: " + Type);
            sb.AppendLine();

            sw.Write(sb.ToString());

            sw.Flush();

            stream.Write(Content, 0, Content.Length);

            stream.Position = 0;

            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, (int)buffer.Length);
            return buffer;
        }
    }
}

<强> POSTDATA

public class PostData
{
    public PostData() { Fields = new List<IPostDataField>(); }

    public List<IPostDataField> Fields { get; set; }

    public Byte[] Export(out string boundary)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            Random r = new Random();
            string tok = "";
            for (int i = 0; i < 14; i++)
                tok += r.Next(10).ToString();

            boundary = "---------------------------" + tok;
            using (StreamWriter sw = new StreamWriter(stream))
            {
                //sw.WriteLine(string.Format("Content-Type: multipart/form-data; boundary=" + boundary.Replace("--", "")));
                //sw.WriteLine();
                //sw.Flush();

                foreach (IPostDataField field in Fields)
                {
                    sw.WriteLine("--" + boundary);
                    sw.Flush();

                    stream.Write(field.Export(), 0, (int)field.Export().Length);
                }

                //1 keer om het af te leren
                //sw.WriteLine();
                sw.WriteLine("--" + boundary + "--");
                sw.Flush();

                stream.Position = 0;

                using (StreamReader sr = new StreamReader(stream))
                {
                    string bla = sr.ReadToEnd();

                    stream.Position = 0;
                    Byte[] toExport = new Byte[stream.Length];
                    stream.Read(toExport, 0, (int)stream.Length);
                    return toExport;
                }

            }
        }
    }
}

答案 1 :(得分:1)

对于任何绊倒这个问题的人来说,使用.NET 4.5(或者通过添加NuGet的Microsoft.Net.Http包的.NET 4.0)更现代的方法是使用Microsoft.Net.Http。这是一个例子:

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;
    }
}

答案 2 :(得分:0)

<强>解

最后我使用WebHelpers类解决了它

Multipart forms from C# client

努力享受。

- 李