Skip to content

Commit 4685bcb

Browse files
huntercaronpieh
authored andcommitted
fix(gatsby-plugin-sharp): url encode file names (#10650)
Uses `encodeURI()` to fix an issue with image files that contain spaces in the name breaking srcset. This encodes the file names with the appropriate `%20` and such.
1 parent c6e9f6b commit 4685bcb

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

packages/gatsby-plugin-sharp/src/__tests__/index.js

+25-2
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,29 @@ describe(`gatsby-plugin-sharp`, () => {
4545
// We expect value to be rounded to 1
4646
expect(result.height).toBe(1)
4747
})
48+
49+
it(`file name works with spaces & special characters`, async () => {
50+
// test name encoding with various characters
51+
const testName = `spaces and '"@#$%^&,`
52+
53+
const queueResult = await queueImageResizing({
54+
file: getFileObject(
55+
path.join(__dirname, `images/144-density.png`),
56+
testName
57+
),
58+
args: { width: 3 },
59+
})
60+
61+
const queueResultName = path.parse(queueResult.src).name
62+
63+
// decoding to check for outputting same name
64+
expect(decodeURIComponent(queueResultName)).toBe(testName)
65+
66+
// regex for special characters above and spaces
67+
// testname should match, the queue result should not
68+
expect(testName.match(/[!@#$^&," ]/)).not.toBe(false)
69+
expect(queueResultName.match(/[!@#$^&," ]/)).not.toBe(true)
70+
})
4871
})
4972

5073
describe(`fluid`, () => {
@@ -298,10 +321,10 @@ describe(`gatsby-plugin-sharp`, () => {
298321
})
299322
})
300323

301-
function getFileObject(absolutePath) {
324+
function getFileObject(absolutePath, name = `test`) {
302325
return {
303326
id: `${absolutePath} absPath of file`,
304-
name: `test`,
327+
name: name,
305328
absolutePath,
306329
extension: `png`,
307330
internal: {

packages/gatsby-plugin-sharp/src/index.js

+5-1
Original file line numberDiff line numberDiff line change
@@ -451,9 +451,13 @@ function queueImageResizing({ file, args = {}, reporter }) {
451451

452452
queueJob(job, reporter)
453453

454+
// encode the file name for URL
455+
const encodedImgSrc = `/${encodeURIComponent(file.name)}.${fileExtension}`
456+
454457
// Prefix the image src.
455458
const digestDirPrefix = `${file.internal.contentDigest}/${argsDigestShort}`
456-
const prefixedSrc = options.pathPrefix + `/static/${digestDirPrefix}` + imgSrc
459+
const prefixedSrc =
460+
options.pathPrefix + `/static/${digestDirPrefix}` + encodedImgSrc
457461

458462
return {
459463
src: prefixedSrc,

0 commit comments

Comments
 (0)