c# - 使用附加模型自动上传文件

标签 c# automation httpwebrequest

我有以下 MVC 4 操作

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SendAttachment(SomeViewModel model, HttpPostedFileBase attachment)
{
    // implementation goes here
}

现在我想使用 HttpWebRequest API 将文件从控制台应用程序上传到此 Controller 操作,但我不知道如何在我的帖子中设置模型和文件数据,以便与 Controller 匹配。

有什么提示吗?

最佳答案

我针对您的问题做了一些更改( Upload files with HTTPWebrequest (multipart/form-data) )。这对我有用。 尝试这样:

服务器端

    [HttpPost]
    public ActionResult SendAttachment(SomeViewModel model, HttpPostedFileBase attachment)
    {
        return View();
    }

    public class SomeViewModel  
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

在控制台应用程序中:

static void Main(string[] args)
    {
        UploadData(
            "http://dissertation.lan/Home/SendAttachment",
            new NameValueCollection()
            { 
                {"attachment", @"C:\Users\_____\Desktop\YourFile.xltx"}
            },
            new NameValueCollection() 
            {
                {"Id", "2"},
                {"Name","Man"}
            });
    }

    public static void UploadData(string url, NameValueCollection files, NameValueCollection nvc)
    {
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

        HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest2.Method = "POST";
        httpWebRequest2.KeepAlive = true;
        httpWebRequest2.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}";

        foreach (string key in nvc.Keys)
        {
            string formitem = string.Format(formdataTemplate, key, nvc[key]);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            memStream.Write(formitembytes, 0, formitembytes.Length);
        }

        memStream.Write(boundarybytes, 0, boundarybytes.Length);

        string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

        foreach (string key in files.Keys)
        {
            string header = string.Format(headerTemplate, key, files[key]);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(files[key], 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();
        }

        httpWebRequest2.ContentLength = memStream.Length;

        Stream requestStream = httpWebRequest2.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();

        WebResponse webResponse2 = httpWebRequest2.GetResponse();

        Stream stream2 = webResponse2.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);

        Console.Write(reader2.ReadToEnd());

        webResponse2.Close();
        httpWebRequest2 = null;
        webResponse2 = null;
    }

结果 enter image description here

enter image description here

关于c# - 使用附加模型自动上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16071194/

相关文章:

c# - 单元测试数据库修改函数?

c# - 在 .NET 中,线程完成任务后会发生什么?我需要管理这个吗?

c# - 如何使 View 完全或部分渲染?

python - 在 Robot Framework 中运行测试套件

android - 获取 Http 请求和响应的大小

C# - 如何通过 HTTP 读取连续的 XML 流

c# - 如何制作使用同一程序集中的静态变量的动态方法?

ms-access - MS Access 2003/2007 VBA - 如何从记录集中获取日期字段并将 dd-MMM-yyyy 格式字符串化?

java - 为我的场景建议一个测试自动化框架

c# - 如何删除/更新 cookie 容器 c# 中的 cookie?