简体   繁体   中英

Uploading a file (image) doesn't work on live server but works on dev

Can't wrap my head around this. The following code works on my local computer but after uploading the site to the server I don't seem to receive the file in the request.

This is my ajax:

dialogUploadPhoto.find('form').submit(function(event) {
    event.preventDefault();
    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serializeForm(), // method below...
        // data: formData,
        processData: false,
        contentType: false,
        cache: false,
        success: function(response) {
            // The response has the correct date on my local server
            dialogUploadPhoto.dialog( "close" );
        },
        error: function (xhr, desc, err){
            // On the live server, the debugger hits
        }
    });
});

The serializeForm method is just a jquery method to append all fields into a FormData instance:

$.fn.serializeForm = function() {
    var form = $(this),
        formData = new FormData();
    var formParams = form.serializeArray();

    $.each(form.find('input[type="file"]'), function(i, tag) {
        $.each($(tag)[0].files, function(i, file) {
            formData.append(tag.name, file);
        });
    });

    $.each(formParams, function(i, val) {
        formData.append(val.name, val.value);
    });

    return formData;
};

The symfony controller method that handles the form looks like this:

/**
 * Matches /admin/upload/foto
 * @Route(
 *     "/upload/foto",
 *     options={"expose": true},
 *     name="admin_upload_foto")
 * @Method({"POST"})
 * @return JsonResponse
 */
public function upload_photo(
    Request $request
) {
    $response = new JsonResponse();

    $newPhoto = new Fotos();
    $photoForm = $this->createForm(PhotoType::class, $newPhoto);
    $photoForm->handleRequest($request);

    if ($photoForm->isSubmitted() && $photoForm->isValid()) {
        // This part is hit on the dev server
    } else if ($photoForm->isSubmitted()) {
        // This part is hit on the live server!
        // categorie contains no errors
        $photoForm['categorie']->getErrors()->__toString());
        // file contains an error: content-type is null;
        $photoForm['file']->getErrors()->__toString());
        $response->setStatusCode(400);
        $response->setData(array("result" => 0, "errors" => $errors));
    } else {
        $response->setStatusCode(400);
        $response->setData(array("result" => 0, "errors" => "Het foto-formulier is niet verzonden naar de server"));
    }
    return $response;
}

The specific error states that the file uploaded file's mime type is null. Does that mean the file is never sent? If I do this: formData.getAll('file') I can see that the file is actually in the bag.

In Chrome's network profiler I can see that the payload does include the file, maybe it is lost along the way?

As requested Here is the var_dump of $_FILES on the live server

array(1) {
  ["photo"]=>
  array(5) {
    ["name"]=>
    array(1) {
      ["file"]=>
      string(8) "test.png"
    }
    ["type"]=>
    array(1) {
      ["file"]=>
      string(9) "image/png"
    }
    ["tmp_name"]=>
    array(1) {
      ["file"]=>
      string(14) "/tmp/phpwy5m9y"
    }
    ["error"]=>
    array(1) {
      ["file"]=>
      int(0)
    }
    ["size"]=>
    array(1) {
      ["file"]=>
      int(25745)
    }
  }
}

Any help would be appreciated

Found a solution but I had to ditch automatic mime type checking for it.

As per symfony documentation I shouldn't care about the file being stored as a string. The mime type checking should be 'guessed' correctly by symfony but the Assert rule for mime types doesn't pick up the mime type of the uploaded file.

I removed the mimetype assert rule and changed my handling method as follows using manual extension checking:

    $newPhoto = new Fotos();
    $photoForm = $this->createForm(PhotoType::class, $newPhoto);
    $photoForm->handleRequest($request);
    //        var_dump($photoForm->getData());
    if ($photoForm->isSubmitted() && $photoForm->isValid()) {
        // $file stores the uploaded PDF file
        /* @var $file UploadedFile */
        $file = $newPhoto->getFile();
        $fileExtension = $file->guessClientExtension();
    //            var_dump($file->guessClientExtension());
        if (($fileExtension === 'png' || $fileExtension === 'jpeg' || $fileExtension === 'jpg')) {
           // Now I know the extension matches the type of files I want to handle
        } else {
           // Now I know the uploaded file is an invalid type
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM