Symfony API : Impossible to upload a picture

tematimtematim FRMember ✭✭

Hello,

I use an HttpClient with the Media plugin and the last version of Xamarin.Forms.

This is my code :
public async Task UploadFilesToServer(string address, byte[] file)
{
MultipartFormDataContent content = new MultipartFormDataContent();
ByteArrayContent baContent = new ByteArrayContent(file);
baContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
baContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("name", "\"media[file]\""));
baContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("filename", "\"image.png\""));
StringContent titleContent = new StringContent("MyTitleText");
content.Add(titleContent, "title");
StringContent descContent = new StringContent("MyDescription");
content.Add(descContent, "description");
content.Add(baContent);

        return await _client.PostAsync(address, content);
    }

My backend :
public function postArticlesAction(Request $request)
{
$uploader = $this->container->get('pm_storage.uploader');
$entityManager = $this->getDoctrine()->getManager();
$user = $this->getUser();
$article = new Article();
$form = $this->createForm(ArticleType::class, $article);

    // Fill form with data sends with request
    $form->submit([
        'title'         => $request->get('title'),
        'description'   => $request->get('description'),
        'media'         => $request->files->get('media')
    ]);

    // Check the validity of data in form
    if(!$form->isValid()) throw new ApiException(Response::HTTP_BAD_REQUEST, 'invalid data request', $form);

    // Add media file into filesystem and get filename generated
    $filename = $uploader->upload($article->getMedia()->getFile());

    // Set new filename provided by filesystem into media part
    $article->getMedia()->setFilename($filename);

    // Persist article in data storage
    $article->setUser($user);
    $entityManager->persist($article);
    $entityManager->flush();


    // Create view used when service succeed
    $view = View::create(null, Response::HTTP_CREATED);
    $view->setLocation('http://{hostname}/{entrypoint}/articles/' . $article->getId());

    return $view;
}

On any browser, the XHR look like :
------WebKitFormBoundary1aF5eiFQb8xX____(hidden chars)
Content-Disposition: form-data; name="title"

MyTitleText
------WebKitFormBoundary1aF5eiFQb8xX____(hidden chars)
Content-Disposition: form-data; name="description"

MyDescription
------WebKitFormBoundary1aF5eiFQb8xX____(hidden chars)
Content-Disposition: form-data; name="media[file]"; filename="image.png"
Content-Type: image/png

------WebKitFormBoundary1aF5eiFQb8xX____(hidden chars)--

How can I send the ByteArrayContent correctly ?

Regards

Sign In or Register to comment.