Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload corruption

Im trying to upload a file to sharepoint

  1. Successful try with just axios is the following enter image description here

  2. Failure if i upload using Guzzle enter image description here enter image description here

Uploaded file at the end is corrupted

enter image description here

like image 508
b00sted 'snail' Avatar asked Apr 13 '26 07:04

b00sted 'snail'


2 Answers

There are a few things you need to modify to get this working (tested on my end):

  1. To get the contents of the file, you need $request->file('file') and then use file_get_contents() on it. You can lose the get() part.

  2. Make sure you're sending the header to accept multipart/form-data too:

    "Accept" => "multipart/form-data"
    
  3. Fields name and filename in a form are two different things. Former is the name of the field while the latter is the name of the file. You need to send both.

Try this:

protected function uploadFile(Request $request){
$file = $request->file('file');
$body = [
          "headers" => [
          "Accept" => "multipart/form-data",
          "Authorization" => "Bearer {$this->token}"
         ],
         "multipart" => [
          "name" => "file",
          "contents" => file_get_contents($file),
          "filename" => $file->getClientOriginalName()
        ]
     ];
return (new Client)->request('POST', 'https://.sharepoint.com/...', $body);
}

P.S. - You can check whether a file is valid or not using isValid():

if ($request->file('file')->isValid()) {
    //
}

Official docs on this: https://laravel.com/docs/7.x/requests#retrieving-uploaded-files

like image 126
Qumber Avatar answered Apr 15 '26 02:04

Qumber


When providing content to be uploaded to Guzzle client as string, Guzzle tries to infer necessary information about the file such as filename, content-type.

You can help Guzzle to infer these information correctly to build the multipart request by passing information about about the filename and content-type in the multipart payload.

[
    //...

    'multipart' => [
        [
            'name' => 'fileName',
            'contents' => $request->file('file')->get(),
            'filename' => $request->file('file')->getName(),
            'headers' => [
               'content-type' => $request->file('file')->getMimeType(),
            ]
        ]
    ]
]
like image 26
Oluwafemi Sule Avatar answered Apr 15 '26 01:04

Oluwafemi Sule