Skip to content

Commit

Permalink
Sanitize filename before upload to prevent issues with spaces and spe…
Browse files Browse the repository at this point in the history
…cial characters in filenames. (#109)
  • Loading branch information
larskarbo authored Dec 1, 2022
1 parent 6180453 commit b66bced
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/next-s3-upload/src/hooks/use-s3-upload.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export const useS3Upload: UseS3Upload = (options = {}) => {
let endpoint = options.endpoint ?? '/api/s3-upload';

let uploadToS3: UploadToS3 = async (file, options = {}) => {
let filename = encodeURIComponent(file.name);
let filename = file.name;

let requestExtras = options?.endpoint?.request ?? {
headers: {},
Expand Down
8 changes: 7 additions & 1 deletion packages/next-s3-upload/src/pages/api/s3-upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ type Options = {

export const uuid = () => uuidv4();

const SAFE_CHARACTERS = /[^0-9a-zA-Z!_\\.\\*'\\(\\)\\\-/]/g;
const safeKey = (value: string) =>
value.replace(SAFE_CHARACTERS, ' ').replace(/\s+/g, '-');

let makeRouteHandler = (options: Options = {}): Handler => {
let route: NextRouteHandler = async function(req, res) {
let missing = missingEnvs();
Expand All @@ -39,9 +43,11 @@ let makeRouteHandler = (options: Options = {}): Handler => {
let bucket = process.env.S3_UPLOAD_BUCKET;

let filename = req.body.filename;
let sanitizedFilename = safeKey(filename);

let key = options.key
? await Promise.resolve(options.key(req, filename))
: `next-s3-uploads/${uuidv4()}/${filename.replace(/\s/g, '-')}`;
: `next-s3-uploads/${uuidv4()}/${sanitizedFilename}`;

let policy = {
Statement: [
Expand Down

1 comment on commit b66bced

@vercel
Copy link

@vercel vercel bot commented on b66bced Dec 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please # to comment.