Skip to content

Commit 6fc83d7

Browse files
fix(plugin-cloud-storage): store processed bytes for cropped and mislabeled client uploads (#18913)
Stacked on #18388. Review and merge #18388 first. ## Summary Direct client uploads with a crop or a wrong MIME type do not store the processed file. A crop returns a 500 error. A file with a wrong MIME type keeps the original bytes in storage, but the document describes the processed file. ## How - The storage plugin runs a second update to save adapter metadata. That update now runs without `uploadEdits`. Before, it applied the crop again and tried to download the file, which failed. `main` already does this. - When Payload corrects the MIME type, `req.file` now points to the corrected copy of the file. Before, only the copy was marked as processed, so the storage plugin skipped the upload. - When a crop and `resizeOptions` are both set, the temp file now gets the cropped and resized bytes. Before, it got only the cropped bytes. ## Tests The resized client-upload test now also covers a cropped upload and an upload with a wrong MIME type. The test collection has an image size, so each case also covers crops together with `imageSizes`. Each case checks that the stored sizes of the main file and the image size are equal to their `filesize` values on the document. Both new cases failed before this change. ## Related work - Stack: #18388 → this PR → #18920 → #18921 - Issue: #18333 --------- Co-authored-by: Jarrod Flesch <[email protected]>
1 parent 210de57 commit 6fc83d7

6 files changed

Lines changed: 64 additions & 11 deletions

File tree

‎packages/payload/src/uploads/cropImage.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { SharpOptions } from 'sharp'
22

3+
import fs from 'fs/promises'
4+
35
import type { SanitizedConfig } from '../config/types.js'
46
import type { PayloadRequest } from '../types/index.js'
57
import type { WithMetadata } from './optionallyAppendMetadata.js'
@@ -61,11 +63,13 @@ export async function cropImage({
6163
adjustedHeight = animatedMetadata.pages ? animatedMetadata.height! : originalHeight
6264
}
6365

66+
const data = file.tempFilePath ? await fs.readFile(file.tempFilePath) : file.data
67+
6468
return {
65-
data: file.data,
69+
data,
6670
info: {
6771
height: adjustedHeight,
68-
size: file.size,
72+
size: data.length,
6973
width: originalWidth,
7074
},
7175
}

‎packages/payload/src/uploads/generateFileData.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,13 @@ export const generateFileData = async <T>({
193193
(isProcessableImage(file.mimetype) || isProcessableImage(detectedFileType.mime))
194194

195195
if (shouldUseDetectedFileType && detectedFileType.mime !== file.mimetype) {
196+
const isRequestFile = file === req.file
196197
file = { ...file, mimetype: detectedFileType.mime }
198+
199+
// Later steps change `file` in place, and storage adapters read `req.file`.
200+
if (isRequestFile) {
201+
req.file = file
202+
}
197203
}
198204

199205
if (!disableLocalStorage) {
@@ -375,7 +381,7 @@ export const generateFileData = async <T>({
375381
delete file.clientUploadContext
376382
delete fileForResize.clientUploadContext
377383
if (file.tempFilePath) {
378-
await fs.writeFile(file.tempFilePath, croppedImage) // write fileBuffer to the temp path
384+
await fs.writeFile(file.tempFilePath, fileForResize.data) // write the edited bytes to the temp path
379385
} else {
380386
req.file = fileForResize
381387
}

‎packages/plugin-cloud-storage/src/hooks/afterChange.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ export const getAfterChangeHook =
9393
// Clear to prevent re-processing
9494
req.file = undefined
9595
req.payloadUploadSizes = undefined
96+
const originalQuery = req.query
97+
req.query = { ...req.query }
98+
delete req.query.uploadEdits
9699

97100
try {
98101
await req.payload.update({
@@ -104,6 +107,7 @@ export const getAfterChangeHook =
104107
req,
105108
})
106109
} finally {
110+
req.query = originalQuery
107111
delete req.context.skipCloudStorage
108112
}
109113

‎test/storage-vercel-blob/client-uploads/collections/ResizedMedia.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,8 @@ import { resizedMediaSlug } from '../../shared.js'
55
export const ResizedMedia: CollectionConfig = {
66
slug: resizedMediaSlug,
77
fields: [],
8-
upload: { resizeOptions: { height: 10, width: 10 } },
8+
upload: {
9+
imageSizes: [{ name: 'thumbnail', height: 5, width: 5 }],
10+
resizeOptions: { height: 10, width: 10 },
11+
},
912
}

‎test/storage-vercel-blob/client-uploads/int.spec.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -131,22 +131,30 @@ describe('@payloadcms/storage-vercel-blob clientUploads', () => {
131131
expect(uploaded).toBeDefined()
132132
})
133133

134-
it('should store processed bytes for a resized client upload', async () => {
134+
it.each([
135+
['resized', 'image/png', ''],
136+
[
137+
'cropped',
138+
'image/png',
139+
'?uploadEdits[crop][unit]=%25&uploadEdits[crop][x]=0&uploadEdits[crop][y]=0&uploadEdits[crop][width]=50&uploadEdits[crop][height]=50&uploadEdits[heightInPixels]=800&uploadEdits[widthInPixels]=800',
140+
],
141+
['mislabeled', 'image/jpeg', ''],
142+
])('should store processed bytes for a %s client upload', async (_, mimeType, query) => {
135143
const file = readFileSync(path.resolve(dirname, '../../uploads/image.png'))
136144
const issued = await issueClientUpload({
137145
collectionSlug: resizedMediaSlug,
138146
filename: 'image.png',
139-
mimeType: 'image/png',
147+
mimeType,
140148
})
141149

142-
await upload(issued.pathname, new Blob([file], { type: 'image/png' }), {
150+
await upload(issued.pathname, new Blob([file], { type: mimeType }), {
143151
access: 'public',
144152
clientPayload: JSON.stringify({
145153
collectionSlug: resizedMediaSlug,
146-
mimeType: 'image/png',
154+
mimeType,
147155
signedReceipt: issued.clientUploadContext.signedReceipt,
148156
}),
149-
contentType: 'image/png',
157+
contentType: mimeType,
150158
handleUploadUrl,
151159
})
152160

@@ -158,12 +166,12 @@ describe('@payloadcms/storage-vercel-blob clientUploads', () => {
158166
clientUploadContext: issued.clientUploadContext,
159167
collectionSlug: resizedMediaSlug,
160168
filename: issued.filename,
161-
mimeType: 'image/png',
169+
mimeType,
162170
size: file.length,
163171
}),
164172
)
165173

166-
const response = await restClient.POST(`/${resizedMediaSlug}`, { body: formData })
174+
const response = await restClient.POST(`/${resizedMediaSlug}${query}`, { body: formData })
167175

168176
expect(response.status).toBe(201)
169177

@@ -173,9 +181,13 @@ describe('@payloadcms/storage-vercel-blob clientUploads', () => {
173181

174182
const { blobs } = await list()
175183
const storedMain = blobs.find(({ pathname }) => pathname.endsWith(`/${doc.filename}`))
184+
const storedThumbnail = blobs.find(({ pathname }) =>
185+
pathname.endsWith(`/${doc.sizes.thumbnail.filename}`),
186+
)
176187

177188
expect(doc.width).toBe(10)
178189
expect(storedMain?.size).toBe(doc.filesize)
190+
expect(storedThumbnail?.size).toBe(doc.sizes.thumbnail.filesize)
179191
})
180192

181193
it("should reject upload when 'x-disallow-access' header is set", async () => {

‎test/storage-vercel-blob/client-uploads/payload-types.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,16 @@ export interface ResizedMedia {
230230
height?: number | null;
231231
focalX?: number | null;
232232
focalY?: number | null;
233+
sizes?: {
234+
thumbnail?: {
235+
url?: string | null;
236+
width?: number | null;
237+
height?: number | null;
238+
mimeType?: string | null;
239+
filesize?: number | null;
240+
filename?: string | null;
241+
};
242+
};
233243
}
234244
/**
235245
* This interface was referenced by `Config`'s JSON-Schema
@@ -453,6 +463,20 @@ export interface ResizedMediaSelect<T extends boolean = true> {
453463
height?: T;
454464
focalX?: T;
455465
focalY?: T;
466+
sizes?:
467+
| T
468+
| {
469+
thumbnail?:
470+
| T
471+
| {
472+
url?: T;
473+
width?: T;
474+
height?: T;
475+
mimeType?: T;
476+
filesize?: T;
477+
filename?: T;
478+
};
479+
};
456480
}
457481
/**
458482
* This interface was referenced by `Config`'s JSON-Schema

0 commit comments

Comments
 (0)