2
votes

I am trying to create integration test for my upload picture action. Raw request created from browser is like below;

POST /api/UpdateImage HTTP/1.1
Host: upload.qwe.com
Authorization: bearer KuThe6Wx/CW1TO/HVS+u3Tov3MRh8qTMDrSvQ09nMnP4OgYp
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1
Content-Length: 375488
Accept-Language: en-us
Accept: */*
Connection: keep-alive
User-Agent: Chrome
Pragma: no-cache
Cache-Control: no-cache

--Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1
Content-Disposition: form-data; name="fileName"

image.jpg
--Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1
Content-Disposition: form-data; name="fileUpload"; filename="image.jpg"
Content-Type: image/jpeg

And my code for integration test;

MultipartContent multipartContent = new MultipartContent();
 multipartContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=Boundary-D60385FA-C164-45B0-A81E-0F6488F8E1E1");
ContentDispositionHeaderValue contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileName"
            };
            multipartContent.Headers.ContentDisposition = contentDispositionHeaderValue;
// StreamContent
        FileStream fileStream = File.Open(@"./Assets/" + fileName, FileMode.Open);
        StreamContent stream = new StreamContent(fileStream);
        multipartContent.Add(stream);
httpRequestMessage.Content = multipartContent;
        return httpRequestMessage;

But I cannot set second part of the data which has Content-Disposition: form-data; name="fileUpload"; filename="image.jpg"

How can I achieve this?

Problem Summary:

enter image description here

1

1 Answers

4
votes

modify the sub HttpContent's Headers, not in the MultipartFormDataContent

        var main = new MultipartFormDataContent(Guid.NewGuid().ToString());
        HttpContent content = new StringContent("image.jpg");
        content.Headers.Clear();
        content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "fileName" };
        main.Add(content);

        content = new StreamContent(new MemoryStream(new byte[] { 1, 2, 3 }));//your file stream, or other base64 string
        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
        content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "fileUpload", FileName="image.jpg" };
        main.Add(content);

        req.Content = main;