Writing

Special Characters in OSS Filenames: URL-Encoding Pitfalls and the Real Fix

2026-06-27

13 mins to read

Share article

In production, a user uploaded a file called Product Doc_问题+答案.docx. The upload succeeded and the file showed up in the list, but clicking preview got nowhere: the spinner turned for a long time and then the pane stayed blank. The backend endpoint that reads the file for further processing simply threw back 500 Parsing failed. At the end of the investigation, the culprit turned out to be that innocent-looking + in the filename.This post is a full post-mortem: from symptom to root cause, from "treating the symptom" to "curing the disease", plus several deep URL-encoding pits I fell into along the way. All of it is hands-on experience you can carry straight into your own project.

1. Background: a file upload system

This is a typical file management system: users upload documents (PDF / DOCX / XLSX…) to object storage (OSS), and the file is then registered in the business database. If "backend processing" is checked, the server fetches the file's URL, then reads and parses its content for further processing.

The data flow looks roughly like this:

Note one key fact: document_url is not just for browser preview. It has at least three consumers:

  1. Browser preview (PDFs go straight into an iframe; Office documents go through an online preview service);
  2. Browser download (window.open);
  3. Backend fetch for processing (the server sends an HTTP request to pull the file content).

Keep this in mind. The whole "why fixing only the frontend doesn't work" part later depends on it.

2. Symptom: upload succeeds, access returns 404

The user uploads Product Doc_问题+答案.docx, and OSS returns an access URL that looks like this:

https://cdn.example.com/files/2026/06/27/Product Doc_问题+答案.docx

This filename hits three kinds of "special characters" at once: a space, Chinese characters, and a plus sign +.

Testing gave a strange picture: the vast majority of files with spaces or Chinese characters worked fine; only the ones with + wouldn't open. The backend read-and-process endpoint also returned 500 Parsing failed for every one of those files. Spaces and Chinese are fine, but + is not, and that is exactly the lead to follow.

3. Digging for the root cause: the "dual identity" of +

3.1 What does + actually mean in a URL?

+ has two contradictory meanings in a URL, depending on where it sits and who parses it:

ContextMeaning of +Source
application/x-www-form-urlencoded (forms / query string)A spaceThe HTML form encoding convention, carried into today's URL standard
The path part of the generic URI syntaxA literal plus sign + (a reserved character in sub-delims)RFC 3986 §2.2

According to RFC 3986, a + in the path should be a literal plus, and a space is what gets encoded as %20. The historical baggage is that form submissions encode spaces as + (to save bytes and avoid %20), and the habit is so deeply ingrained that many servers, gateways and CDNs also treat + as a space when parsing the path.

In one sentence: + in the query = a space; in the path it should = a literal plus, but many servers don't play by the rules and decode a + in the path into a space as well.

3.2 How OSS "loses" the file

An OSS object key is essentially just a string of bytes. On access, the whole key serves as the path, and the server URL-decodes the path once to restore the real key before looking it up. When the browser requests .../Product Doc_问题+答案.docx, OSS decodes the + in the path into a space, so the key it actually looks for becomes Product Doc_问题 答案.docx (a space, not a plus, between 问题 and 答案). That doesn't match the real key → NoSuchKey → 404 → the file won't open.

3.3 Nailing it down with curl (turning a guess into proof)

Go straight to curl -I (send only a HEAD request to see the status code, without downloading the body). Change only the + in the filename, once as a bare + and once as %2B, with every other character encoded normally:

# Bare + version (everything else encoded, only + left as is)
curl -sI -o /dev/null -w "%{http_code} " 'https://cdn.example.com/files/2026/06/27/Product%20Doc_%E9%97%AE%E9%A2%98+%E7%AD%94%E6%A1%88.docx'
# → 404

# Encoded version (+ → %2B)
curl -sI -o /dev/null -w "%{http_code} " 'https://cdn.example.com/files/2026/06/27/Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx'
# → 200

Bare + → 404, %2B → 200. The + is the only variable, so the causality is pinned down. It also proves in passing that the key stored in OSS really does contain a literal + (send %2B in the request, OSS decodes it back to +, and the lookup hits).

A debugging method: use curl -I to decouple "storage-layer reachability" from "upper-layer rendering / preview". A 200 means file access is fine, so go look at the preview logic; only a 404 / 403 points to a storage or encoding problem. Don't start by staring at the preview component in a debugger.

4. Why does it still slip through when "it's clearly encoded"? The encodeURI trap

The code actually did encode already:

const encodedUrl = computed(() => encodeURI(documentUrl.value));

encodeURI handles spaces (→ %20) and Chinese characters (→ %xx), which is why filenames with spaces or Chinese worked. But + is precisely what it does not encode. This is the classic difference between it and encodeURIComponent:

FunctionCharacters left unencodedEncodes +?Intended use
encodeURIA-Za-z0-9 - _ . ! ~ * ' ( ), plus ; , / ? : @ & = + $ #❌ NoEncoding a "whole URL", preserving structural characters such as / : ? #
encodeURIComponentA-Za-z0-9 - _ . ! ~ * ' ( )✅ Encodes it as %2BEncoding "one piece of a URL", escaping structural characters too

encodeURI preserves structurally meaningful characters like + / : ? # & = as the "skeleton of the URL". That is right for encoding a whole URL, but wrong for encoding a filename: a + in a filename is data, not structure.

Conclusion: to encode a filename (one segment of the path), use encodeURIComponent, not encodeURI. This trap is the best hidden of all, because it "looks fine" for spaces and Chinese characters and tricks you into believing the encoding is correct.

5. The first fix: a utility function + replacing the "read" paths

The idea: apply encodeURIComponent to every segment of the path, segment by segment (/ must not be encoded, so split on /, encode each segment, then join them back):

// Encode the "unencoded" OSS file URL returned by the backend into a form that is safe to access.
export const encodeOssUrl = (raw: string): string => {
  if (!raw) return "";
  const qIdx = raw.indexOf("?");
  const query = qIdx >= 0 ? raw.slice(qIdx) : "";       // keep the query (signature etc.) as is
  const noQuery = qIdx >= 0 ? raw.slice(0, qIdx) : raw;
  const schemeEnd = noQuery.indexOf("://");
  const pathStart = schemeEnd >= 0 ? noQuery.indexOf("/", schemeEnd + 3) : -1;
  if (pathStart < 0) return raw;
  const origin = noQuery.slice(0, pathStart);
  const encodedPath = noQuery
    .slice(pathStart)
    .split("/")
    .map(seg => {
      let s = seg;
      try { s = decodeURIComponent(seg); } catch { /* illegal escapes such as a bare %: keep as is */ }
      return encodeURIComponent(s);
    })
    .join("/");
  return origin + encodedPath + query;
};

I replaced encodeURI(...) with encodeOssUrl(...) in the preview and download call sites. Self-test: preview and download both worked for files with +! …and I thought I was done. But the backend read-and-process endpoint was still returning 500 Parsing failed.

6. The real root: the read side and the write side must agree

The first version only fixed the "read" paths, but document_url has one more consumer the frontend can't reach: the backend fetch. What decides whether the backend can fetch the file is the value written into the database. The register API had been receiving the bare URL all along:

insertDocument({
  document_url: f.fileUrl,   // ❌ bare URL, contains a literal +
  file_name: f.name,
  enable_status: withProcess ? 1 : 0,
});

The chain: the bare URL (with +) is written to the DB → the backend reads it and sends an HTTP request → + is treated as a space → the content can't be fetched → 500 Parsing failed. Meanwhile the frontend's preview and download have encodeOssUrl as a safety net, so "reading" looks fine, and that is exactly what masked the problem at the write entry point.

Key insight: an encoding safety net on the frontend's "read" side cannot rescue dirty data that was "written" in. The true source is the value that goes into the database.

Fixing the write entry point:

insertDocument({
  // Encode before storing: the backend fetches by this URL, and a bare + / space / Chinese character makes the fetch fail
  document_url: encodeOssUrl(f.fileUrl),   // ✅
  file_name: f.name,                        // display name stays as is, not encoded
  enable_status: withProcess ? 1 : 0,
});

Do not encode file_name. It is the display name meant for humans, and encoding it would show %2B in the list. Encode the URL field, keep the display field verbatim, and keep the two responsibilities separate.

After this change, the whole chain is self-consistent:

StageURL formResult
Returned by the OSS uploadBare …+…—
Registered in the DBencodeOssUrl → …%2B…The DB stores the encoded form
Backend fetch for processingRequests %2B → OSS decodes it back to +✅ Hit, fetch succeeds
List response → preview / downloadThe DB's …%2B… goes through encodeOssUrl again (idempotent)✅ Hit

7. Four hidden pits (the best part)

Pit 1: Idempotency — don't double-encode %2B into %252B

Once the write entry point encodes, the DB already stores …%2B…, and the frontend calls encodeOssUrl once more when "reading". If the implementation "blindly encodes again", the % in %2B gets encoded again into %25 → it becomes the double-encoded %252B, and OSS can't find that either. The solution: first restore with decodeURIComponent, then encodeURIComponent, so the output is the same whether the input is a bare URL or an already-encoded one. That is idempotency: f(f(x)) === f(x). It is the precondition for "the read side and the write side share one function" to hold. (decodeURIComponent throws on a bare %, as in 50%off.xlsx, so a try/catch fallback is needed.)

Pit 2: The "second encoding" for third-party online preview

Browsers can't render Office documents directly, so Microsoft's online viewer is commonly used:

const officeUrl = computed(
  () => `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(encodedUrl.value)}`
);

There are two layers of encoding here, and neither can be skipped: ① encodedUrl is already a path-safe URL (+ → %2B); ② it is stuffed into the Office URL as the src query parameter, so the whole thing gets encodeURIComponent once more. The Office server decodes one layer off src, gets a clean URL back, and then fetches from OSS. Leave out the second layer, and the & : / inside src break the structure of Office's own URL, and the preview fails outright.

Whenever you "use one URL as a parameter of another URL", the parameter layer always needs encodeURIComponent, and it must be applied on top of "a safe URL that has already been processed".

Pit 3: Don't damage the query (signed URLs)

Accessing a private bucket requires a signature, ?Expires=...&Signature=..., and the signature may itself contain + / %2B. But the query is computed by the backend according to an algorithm, and the frontend must never touch it (change one character and the signature is invalid). So encodeOssUrl splits at ?, encodes only the path part, and appends the query back untouched.

Pit 4: # is part of the filename, not a fragment

# is perfectly legal in Windows / macOS filenames (会议纪要#3.docx, "meeting notes #3"), but in a URL it marks the fragment anchor. In the first version I casually wrote split("#")[0] to strip the fragment, which chopped off the whole #3.docx and produced …/会议纪要, creating yet another file that wouldn't open. OSS direct links have no fragment; a # in a filename should be encoded as %23 and treated as data, not cut off as a separator.

The following cases can be used directly as regression tests (actual output):

Product Doc_问题+答案.docx  →  Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx
report&final.pdf           →  report%26final.pdf
50%off.xlsx                →  50%25off.xlsx          ← a bare % is handled correctly too
会议纪要#3.docx             →  %E4%BC%9A%E8%AE%AE%E7%BA%AA%E8%A6%81%233.docx   ← # → %23, not truncated
a b  c.txt                 →  a%20b%20%20c.txt       ← consecutive spaces
x.docx?Expires=1&Sig=a+b   →  ...x.docx?Expires=1&Sig=a+b   ← query kept as is

8. Treating the symptom vs. curing the disease

The "encode uniformly at the access layer" approach above treats the symptom. It works, but it requires every single place that consumes the URL to remember to encode, and missing one spot means a failure (I missed the write entry point). The cure: make the object key URL-safe from the very beginning, so special characters never get a chance to enter the URL at all.

Symptom: encode at the access layerCure: safe keys
ApproachEvery consumer uses encodeOssUrlAt upload, the key is {date}/{uuid}.{ext}; the original name is stored in a DB field
Who changesFrontend (or each consumer)Backend upload logic + a file_name field in the DB
ProsSmall change, rescues existing dataURLs are always safe; all edge cases disappear at once
ConsRelies on no spot being missed; has edge casesNeeds backend changes; you lose "reading the filename off the URL"
Original name on downloadUse the encoded URL directlyFilled back in via Content-Disposition

With the cure in place, how do you keep "the download still has the original Chinese filename"? Through the Content-Disposition response header, using RFC 5987's filename* for non-ASCII names:

Content-Disposition: attachment;
  filename="fallback.docx";
  filename*=UTF-8''Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx

filename (the ASCII fallback) is for old browsers and filename* (UTF-8 percent-encoded) is for modern ones; the downloaded file is still named Product Doc_问题+答案.docx.

One more class of edge cases that encoding can't save

  1. A bare ? in the filename: syntactically it cannot be told apart from the query delimiter (fortunately Windows forbids ? in filenames anyway, so it is rare in practice);
  2. Unicode normalization differences: filenames uploaded from macOS are in NFD (the decomposed form), while OSS / Windows store them in NFC. They look identical to the eye but the bytes differ, so the key simply doesn't match. Percent-encoding escapes byte by byte and can't help when the bytes themselves are inconsistent.

These two points are the hard reasons that push the "safe key" approach to the top.

9. What about existing data?

After the fix shipped, new files were fine, but the historical records in the DB still held bare URLs: preview and download still work thanks to the encodeOssUrl safety net on the read path, but a backend re-fetch using the bare URL will still fail. So existing data has to be handled separately: have the backend run a one-off script that batch-encodes document_url in the DB (the script must be idempotent too), or re-trigger registration / processing for the affected files.

10. Pitfall checklist (take it as is)

  • Encode filenames / path segments with encodeURIComponent, not encodeURI
  • Encode segment by segment (split on /); don't encode the path separator / itself
  • Share one idempotent encoding function between the read side and the write side (decode-then-encode)
  • Encode the URL field; keep the display field (file_name) verbatim
  • Encode only the path, leave the query alone (a signed URL dies with a single change)
  • Encode # as %23; don't cut it off as a fragment
  • For "a URL as a parameter", wrap one more layer of encodeURIComponent (Office / any online preview)
  • When debugging, check the status code with curl -I first, decoupling storage reachability from upper-layer rendering
  • Cure it properly if you can: safe uuid keys + original name in the DB + Content-Disposition on download
  • Don't forget to migrate existing data

11. Summary in one sentence

The disaster caused by a single + is, at its core, a "read/write consistency" problem in URL encoding: + has two identities, "space" and "literal plus", and encodeURI happens not to encode it. The real fix is not on the "read" side (preview / download) but on the "write" side (the value that goes into the database). The most robust approach is to make object keys URL-safe from birth.


References