Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Sanitize filename before upload to prevent issues with spaces and special characters in filenames. #109

Merged
merged 2 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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