title: Configuring Uppy to Use Multipart Uploads with Laravel/Vue
body: <p><strong>I figured it out</strong></p>
  <p>This was the missing piece. Once I clean up my code, I'll post an answer so that hopefully the next poor soul that has to deal with this will not have to go through the same hell I went through ;)</p>
  <pre class="lang-php prettyprint-override"><code>$command = $client-&gt;getCommand('UploadPart', array(
      'Bucket' =&gt; 'the-bucket-name',
      'Key' =&gt; $key,
      'PartNumber' =&gt; $partNumber,
      'UploadId' =&gt; $uploadId,
      'Body' =&gt; '',
  ));
  
  $signedUrl = $client-&gt;createPresignedRequest($command, '+20 minutes');
  $presignedUrl = (string)$signedUrl-&gt;getUri();
  return response()-&gt;json(['url' =&gt; $presignedUrl]);
  </code></pre>
  <hr />
  <p>I'm trying to figure out how to configure my server to work with Uppy for uploading multipart uploads to AWS S3 by using the CompanionUrl option. <a href="https://uppy.io/docs/aws-s3-multipart/#createMultipartUpload-file" rel="nofollow noreferrer">https://uppy.io/docs/aws-s3-multipart/#createMultipartUpload-file</a>.</p>
  <p>This is where I got the idea to go this route <a href="https://github.com/transloadit/uppy/issues/1189#issuecomment-445521442" rel="nofollow noreferrer">https://github.com/transloadit/uppy/issues/1189#issuecomment-445521442</a>.</p>
  <p>I can't figure this out and I feel like others have been stuck as well with no answer, so I'm posting what I've come up with so far in trying to get Uppy to work with multipart uploads using Laravel/Vue.</p>
  <hr />
  <p>For the Vue component I have this:</p>
  <pre class="lang-html prettyprint-override"><code>&lt;template&gt;
  &lt;div&gt;
      &lt;a id=&quot;uppy-trigger&quot; @click=&quot;isUppyOpen = !isUppyOpen&quot;&gt;Open Uppy&lt;/a&gt;
  
      &lt;dashboard-modal
          :uppy=&quot;uppy&quot;
          :open=&quot;isUppyOpen&quot;
          :props=&quot;{trigger: '#uppy-trigger'}&quot;
      /&gt;
  &lt;/div&gt;
  &lt;/template&gt;
  
  &lt;script&gt;
  import Uppy from '@uppy/core'
  import AwsS3Multipart from '@uppy/aws-s3-multipart';
  import '@uppy/core/dist/style.css';
  import '@uppy/dashboard/dist/style.css';
  
  export default {
      components: {
          'dashboard-modal': DashboardModal,
      },
  
      data() {
          return {
              isUppyOpen: false,
          }
      },
  
      computed: {
          // Uppy Instance
          uppy: () =&gt; new Uppy({
              logger: Uppy.debugLogger
          }).use(AwsS3Multipart, {
              limit: 4,
              companionUrl: 'https://mysite.local/',
          }),
      },
  
      beforeDestroy () {
          this.uppy.close();
      },
  }
  &lt;/script&gt;
  </code></pre>
  <hr />
  <p>Then for the routing I've added this to my web.php file.</p>
  <pre class="lang-php prettyprint-override"><code>// AWS S3 Multipart Upload Routes
  Route::name('s3.multipart.')-&gt;prefix('s3/multipart')
      -&gt;group(function () {
          Route::post('/', ['as' =&gt; 'createMultipartUpload', 'uses' =&gt; 'AwsS3MultipartController@createMultipartUpload']);
          Route::get('{uploadId}', ['as' =&gt; 'getUploadedParts', 'uses' =&gt; 'AwsS3MultipartController@getUploadedParts']);
          Route::get('{uploadId}/{partNumber}', ['as' =&gt; 'signPartUpload', 'uses' =&gt; 'AwsS3MultipartController@signPartUpload']);
          Route::post('{uploadId}/complete', ['as' =&gt; 'completeMultipartUpload', 'uses' =&gt; 'AwsS3MultipartController@completeMultipartUpload']);
          Route::delete('{uploadId}', ['as' =&gt; 'abortMultipartUpload', 'uses' =&gt; 'AwsS3MultipartController@abortMultipartUpload']);
      });
  </code></pre>
  <p>Basically what is happening is that I've set the &quot;companionUrl&quot; to &quot;https://mysite.local/&quot;, then Uppy will send five requests when uploading a multipart upload file to these routes, ie &quot;https://mysite.local/s3/multipart/createMultipartUpload&quot;.</p>
  <hr />
  <p>I then created a controller to handle the requests:</p>
  <pre class="lang-php prettyprint-override"><code>&lt;?php
  
  namespace App\Http\Controllers;
  
  use Aws\S3\S3Client;
  use Illuminate\Http\Request;
  
  class AwsS3MultipartController extends Controller
  {
      public function createMultipartUpload(Request $request)
      {
          $client = new S3Client([
              'version' =&gt; 'latest',
              'region'  =&gt; 'us-east-1',
          ]);
  
          $key = $request-&gt;has('filename') ? $request-&gt;get('filename') : null;
  
          $type = $request-&gt;has('type') ? $request-&gt;get('type') : null;
  
          if (!is_string($key)) {
              return response()-&gt;json(['error' =&gt; 's3: filename returned from &quot;getKey&quot; must be a string'], 500);
          }
  
          if (!is_string($type)) {
              return response()-&gt;json(['error' =&gt; 's3: content type must be a string'], 400);
          }
  
          $response = $client-&gt;createMultipartUpload([
              'Bucket'        =&gt; 'the-bucket-name',
              'Key'           =&gt; $key,
              'ContentType'   =&gt; $type,
              'Expires'       =&gt; 60
          ]);
  
          $mpuKey = !empty($response['Key']) ? $response['Key'] : null;
          $mpuUploadId = !empty($response['UploadId']) ? $response['UploadId'] : null;
  
          if (!$mpuKey || !$mpuUploadId) {
              return response()-&gt;json(['error' =&gt; 'Unable to process upload request.'], 400);
          }
  
          return response()-&gt;json([
              'key'       =&gt; $mpuKey,
              'uploadId'  =&gt; $mpuUploadId
          ]);
      }
  
      public function getUploadedParts($uploadId)
      {
          // Haven't configured this route yet as I haven't made it this far.
          return $uploadId;
      }
  
      public function signPartUpload(Request $request, $uploadId, $partNumber)
      {
          $client = new S3Client([
              'version' =&gt; 'latest',
              'region'  =&gt; 'us-east-1',
          ]);
  
          $key = $request-&gt;has('key') ? $request-&gt;get('key') : null;
  
          if (!is_string($key)) {
              return response()-&gt;json(['error' =&gt; 's3: the object key must be passed as a query parameter. For example: &quot;?key=abc.jpg&quot;'], 400);
          }
  
          if (!intval($partNumber)) {
              return response()-&gt;json(['error' =&gt; 's3: the part number must be a number between 1 and 10000.'], 400);
          }
  
          // Creating a presigned URL. I don't think this is correct.
          $cmd = $client-&gt;getCommand('PutObject', [
              'Bucket'        =&gt; 'the-bucket-name',
              'Key'           =&gt; $key,
              'UploadId'      =&gt; $uploadId,
              'PartNumber'    =&gt; $partNumber,
          ]);
  
          $response = $client-&gt;createPresignedRequest($cmd, '+20 minutes');
          $presignedUrl = (string)$response-&gt;getUri();
  
          return response()-&gt;json(['url' =&gt; $presignedUrl]);
      }
  
      public function completeMultipartUpload(Request $request, $uploadId)
      {
          $client = new S3Client([
              'version' =&gt; 'latest',
              'region'  =&gt; 'us-east-1',
          ]);
  
          $key = $request-&gt;has('key') ? $request-&gt;get('key') : null;
  
          $parts = json_decode($request-&gt;getContent(), true)['parts'];
  
          if (!is_string($key)) {
              return response()-&gt;json(['error' =&gt; 's3: the object key must be passed as a query parameter. For example: &quot;?key=abc.jpg&quot;'], 400);
          }
  
          if (!is_array($parts) || !$this-&gt;arePartsValid($parts)) {
              return response()-&gt;json(['error' =&gt; 's3: &quot;parts&quot; must be an array of {ETag, PartNumber} objects.'], 400);
          }
  
  
          // The completeMultipartUpload method fails with the following error.
  
          // &quot;Error executing &quot;CompleteMultipartUpload&quot; on &quot;https://the-bucket-name.s3.amazonaws.com/NewProject.png?uploadId=nlWLdbNgB9zgarpLBXnj17eOIGAmQM_xyBArymtwdM71fhbFvveggDmL6fz4blz.B95TLhMatDvodbMb5p2ZMKqdlLeLFoSW1qcu33aRQTlt6NbiP_dkDO90DFO.pWGH&quot;; AWS HTTP error: Client error: `POST https://the-bucket-name.s3.amazonaws.com/NewProject.png?uploadId=nlWLdbNgB9zgarpLBXnj17eOIGAmQM_xyBArymtwdM71fhbFvveggDmL6fz4blz.B95TLhMatDvodbMb5p2ZMKqdlLeLFoSW1qcu33aRQTlt6NbiP_dkDO90DFO.pWGH` resulted in a `400 Bad Request` response:
          //     &lt;Error&gt;&lt;Code&gt;InvalidPart&lt;/Code&gt;&lt;Message&gt;One or more of the specified parts could not be found.  The part may not have be (truncated...)
          //  InvalidPart (client): One or more of the specified parts could not be found.  The part may not have been uploaded, or the specified entity tag may not match the part's entity tag. - &lt;Error&gt;&lt;Code&gt;InvalidPart&lt;/Code&gt;&lt;Message&gt;One or more of the specified parts could not be found.  The part may not have been uploaded, or the specified entity tag may not match the part's en&quot;
  
          $result = $client-&gt;completeMultipartUpload([
              'Bucket'          =&gt; 'the-bucket-name',
              'Key'             =&gt; $key,
              'UploadId'        =&gt; $uploadId,
              'MultipartUpload' =&gt; [
                  'Parts' =&gt; $parts,
              ],
          ]);
  
          return response()-&gt;json(['location' =&gt; $result['location']]);
      }
  
      public function abortMultipartUpload($uploadId)
      {
          // Haven't configured this route yet as I haven't made it this far.
          return $uploadId;
      }
  
      private function arePartsValid($parts)
      {
          // Validation for the parts will go here, but returning true for now.
          return true;
      }
  }
  </code></pre>
  <hr />
  <hr />
  <p>I can upload a multipart file fine purely PHP/server-side. For huge files though, this isn't going to work though since I would have to wait for the upload to finish on my server, then upload it to AWS in the parts.</p>
  <pre class="lang-php prettyprint-override"><code>$s3_client = new S3Client([
      'version' =&gt; 'latest',
      'region'  =&gt; 'us-east-1',
  ]);
  $bucket = 'the-bucket-name';
  $tmp_name = $request-&gt;file('file')-&gt;getPathname();
  $folder = Carbon::now()-&gt;format('Y/m/d/');
  $filename = pathinfo($request-&gt;file('file')-&gt;getClientOriginalName(), PATHINFO_FILENAME);
  $extension = $extension = pathinfo($request-&gt;file('file')-&gt;getClientOriginalName(), PATHINFO_EXTENSION);
  $timestamp = Carbon::now()-&gt;format('H-i-s');
  $name = &quot;{$folder}{$filename}_{$timestamp}.{$extension}&quot;;
  
  $response = $s3_client-&gt;createMultipartUpload([
      'Bucket' =&gt; $bucket,
      'Key'    =&gt; $name,
  ]);
  
  $uploadId = $response['UploadId'];
  
  $file = fopen($tmp_name, 'r');
  $parts = [];
  $partNumber = 1;
  while (! feof($file)) {
      $result = $s3_client-&gt;uploadPart([
          'Bucket'     =&gt; $bucket,
          'Key'        =&gt; $name,
          'UploadId'   =&gt; $uploadId,
          'PartNumber' =&gt; $partNumber,
          'Body'       =&gt; fread($file, 5 * 1024 * 1024),
      ]);
  
      $parts[] = [
          'PartNumber' =&gt; $partNumber++,
          'ETag'       =&gt; $result['ETag'],
      ];
  }
  
  $result = $s3_client-&gt;completeMultipartUpload([
      'Bucket'          =&gt; $bucket,
      'Key'             =&gt; $name,
      'UploadId'        =&gt; $uploadId,
      'MultipartUpload' =&gt; [
          'Parts' =&gt; $parts,
      ],
  ]);
  </code></pre>
  <p>What I believe is happening is that Uppy is handling the <code>while</code> loop part client-side. In order to do that, I have to return a pre-signed URL Uppy can use, but the pre-signed URL I'm currently returning isn't correct.</p>
  <p>One thing I noted is that when I step through the while loop when initiating the multipart upload purely server-side, no file is uploaded to my bucket until the <em>completeMultipartUpload</em> method is fired. If however, I step through the parts being uploaded via Uppy, the parts seem to be being uploaded as the final file and each part is just overwriting the previous part. I'm then left with a fragment of the file, ie the last 3.5MB of a 43.5MB file.</p>