Skip to main content
Version: 2.x

File uploads

To upload files to Front-Commerce, two main strategies are possible:

  1. Using an express based route to handle the upload
  2. Sending the file with a GraphQL mutation

Depending on the customer workflow and various technical details one or the other can be more suited.

With an express based route

In this strategy, on the frontend you would typically have a form with a file input so that the user can pick a file. This form must have the enctype attribute set to multipart/form-data and must be configured to post to an express based route. For instance:

<form action="/my/express/route" encType="multipart/form-data">
<p>
<label htmlFor="file">Choose a file</label>
<input type="file" name="file" />
</p>
<p>
<button>Upload</button>
</p>
</form>

In this example, when the customer picks a file and submits the form, the file will be sent to the URL /my/express/route. To create such route, please refer to the add custom endpoints to your server guide. To ease the file upload handling, you can use the express-fileupload package.

note

The request to upload the file can also be issued with fetch or XMLHttpRequest

With a GraphQL mutation

In this strategy, the file will be sent by passing it as a parameter to a GraphQL mutation as a base64 encoded string. Here again, you would typically have a form but instead of directly submitting it, a submit event handler would read the file content and trigger the mutation with its content. For instance:

import React from "react";
import { useLazyQuery } from "react-apollo";
import SendFileMutation from "./SendFileMutation.gql";

const UploadForm = () => {
const [sendFile] = useLazyQuery(SendFileMutation);
const uploadFile = (e) => {
const file = e.target.elements.namedItem("file").files.item(0);
const reader = new FileReader();
reader.onload = () => {
sendFile({ variables: { file: reader.result } });
};
reader.readAsDataURL(file);
e.preventDefault();
};
return (
<form onSubmit={uploadFile}>
<p>
<label htmlFor="file">Choose a file</label>
<input type="file" name="file" />
</p>
<p>
<button>Upload</button>
</p>
</form>
);
};

export default UploadForm;
mutation SendFileMutation($file: String!) {
sendFileMutation(file: $file) {
success
errorMessage
# and any other field depending on the actual result of the mutation
}
}

For that example to work, the mutation SendFileMutation must be defined and implemented in a custom GraphQL module.


Feel free to contact us if you have questions or remark on this topic.