Cypress测试中Google Cloud Storage图片上传后内容损坏问题
Fixing Corrupted Image Uploads to Google Cloud Storage with Cypress
Let's break down why your images are getting corrupted and fix it step by step:
Key Issues in Your Current Code
- Fixture Reading Mode:
cy.fixture()defaults to reading files as base64 strings, but converting this to Blob can introduce encoding mismatches for binary files like images, leading to corruption. - Incorrect Content-Type Header: Manually setting
Content-Type: image/pngwhen sending FormData breaks the auto-generatedmultipart/form-databoundary that browsers use to properly transmit form data. - Unnecessary CORS Headers: The
Access-Control-*headers you're setting are server-side configurations—adding them to the client XHR request has no effect and can interfere with proper request handling.
Fixed Code Implementation
Here's the corrected version of your commands:
Cypress.Commands.add('fileUpload', (url, fileName) => { const method = 'PUT'; const fileType = 'image/png'; // Read fixture as raw binary data (skip base64 encoding) cy.fixture(fileName, { encoding: null }).then((fileBuffer) => { // Convert raw binary buffer directly to Blob const blob = new Blob([fileBuffer], { type: fileType }); // Build FormData (browser auto-handles Content-Type) const formData = new FormData(); formData.set('file', blob, fileName); // Execute request cy.rawFormRequest(method, url, formData, (response) => { cy.log(JSON.stringify(response)); }); }); }); Cypress.Commands.add('rawFormRequest', (method, url, formData, done) => { const xhr = new XMLHttpRequest(); xhr.open(method, url); // Remove all manual Content-Type and CORS header overrides xhr.onload = function () { cy.log('Upload successful'); done(xhr); }; xhr.onerror = function (error) { cy.log('Upload failed'); cy.log(JSON.stringify(error)); done(xhr); }; xhr.send(formData); });
Why This Works
- Raw Fixture Reading: Using
{ encoding: null }tells Cypress to read the image as a raw binary buffer, preserving the exact byte data of the original file. - Direct Blob Conversion: Creating a Blob directly from the raw buffer skips error-prone base64 encoding/decoding steps that were corrupting your image.
- Proper FormData Handling: Letting the browser auto-generate the
Content-Typeheader ensures the multipart boundary is correctly set, so Google Cloud Storage can parse the file data without corruption. - Cleaned Up Headers: Removing unnecessary CORS headers eliminates potential conflicts—bucket-level CORS policies are what control cross-origin access for GCS.
Additional Checks
- Confirm your GCS bucket's CORS policy allows
PUTrequests from your Cypress test origin. - Double-check that
fileTypematches your image's actual MIME type (e.g.,image/jpegfor JPGs) to ensure correct handling by GCS.
内容的提问来源于stack exchange,提问作者opike
相关产品推荐
相关产品推荐

