0

I have a service with the method which gets three parameters which should be sent to the server.

setMainPhotoFor: function(file, petName, petId) {
            ...
}

I have the following solution:

Client side

services.js

setMainPhotoFor: function(file, pet) {
            var baseServerApiUrl = configuration.ServerApi;
            var data = new FormData();

            data.append("image", file);
            data.append("petName", pet.Name);
            data.append("petId", pet.ID);

            $http.post(baseServerApiUrl + '/pictures/main-picture/add', data, {
                headers: { "Content-Type": undefined }
            });
        }

Server side

PicturesApiController

[HttpPost]
[Route("main-picture/add")]
public async Task<HttpResponseMessage> SetMainPicture()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    var provider = new MultipartMemoryStreamProvider();

    await Request.Content.ReadAsMultipartAsync(provider);

    MemoryStream mainPicture = new MemoryStream(await provider.Contents[0].ReadAsByteArrayAsync());
    string petName = await provider.Contents[1].ReadAsStringAsync();
    int petId;

    if (!int.TryParse(await provider.Contents[2].ReadAsStringAsync(), out petId))
    {
        //...
    }
    //...

But in my opinion it doesn't look good. Can anybody suggest a right and more elegant solution for this task?

Sergey_T
  • 538
  • 9
  • 14

2 Answers2

0

to send multipart form with angular add th options like this:

$http.post(baseServerApiUrl + '/pictures/main-picture/add', data, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        });
user3227295
  • 2,168
  • 1
  • 11
  • 17
0

I have answered this before here with server side sample code.

Basically you should stream the content and put your dto in a header. I've tried many ways and this is the best way in my opinion.

Community
  • 1
  • 1
ManOVision
  • 1,853
  • 1
  • 12
  • 14