user938363
user938363

Reputation: 10350

Content-Type: application/xml submitted when fetch PUT with pre signed URL for jpg image file

In the react native 0.70.x app, fetch PUT is used to upload a jpg image file with pre signed URL acquired from backend nodejs server. Content-Type: image/jpeg is used for generating pre signed URL on backend nodejs server. However when uploading a jpg image file in React Native frontend with fetch PUT, the Content-Type: application/xml is used instead of 'image/jpeg`. Here is the React Native code:

import ReactNativeBlobUtil from 'react-native-blob-util';  //dependency. v0.19.2
uploadToOSS : async (preSignedUrl, filePath, extension, filename) => {   //filename, 23200/fxxxxx-xxxxxx.jpg, is used as object key for OSS
   var fileData;
   try {
     const contentTypeMap = {
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        png: 'image/png',
        tiff: 'image/tiff',
        tif: 'image/tiff',  
        mp4: 'video/mp4',
        mov: 'video/mov',
      };

     fileData = await ReactNativeBlobUtil.fs.readFile(filePath, 'base64');
     const formData = new FormData();

      //formData.append('key', filename);
      formData.append('file', fileData, {type:contentTypeMap[extension]});//<< type is image/jpeg
      const response = await fetch(preSignedUrl, {
        method: 'PUT',
        body: formData,  //<<==base64 data read by ReactNativeBlobUtil.fs.readFile
      }); 

     console.log("respnose in uploadtooss : ", response);
     if (response.ok) {  //fetch successful
       return true;
     } else {
       return false;
     };
   } catch (err) {
     console.log("upload to OSS failed : ", err);
     return false;
   }; 

The returned response has 403 with content type of application/xml in submitting headers. Here is the console output of fetch response:

 LOG  respnose in uploadtooss :  {"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "f0071d9c-f218-4b26-bcaf-0d7e8983bbf3", "offset": 0, "size": 1127}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "f0071d9c-f218-4b26-bcaf-0d7e8983bbf3", "offset": 0, "size": 1127}}, "bodyUsed": false, "headers": {"map": {"connection": "keep-alive", "content-length": "1127", "content-type": "application/xml"(<<<<<======), "date": "Thu, 08 Feb 2024 22:18:27 GMT", "server": "AliyunOSS", "x-oss-ec": "0002-00000040", "x-oss-request-id": "65C5533307D4B93635D7511C", "x-oss-server-time": "95"}}, "ok": false, "status": 403, "statusText": "", "type": "default", "url": "https://oss-hz-1.oss-cn-xxxxxx.aliyuncs.com/22790-fCWOVB_1000000021.jpg?OSSAccessKeyId=LTAI5t5axvqwo2qGnxxxxxxxx&Expires=1707432506&Signature=m60o9WszMIcfzF8mHWQ2HDPHsHW%3D"}

Since the pre signed URL is generated with Content-Type:image/jpeg, how to force fetch PUT to upload image file with the same image/jpeg content type? Or shall other REST API be used for uploading image file with pre signed URL.

Upvotes: 0

Views: 53

Answers (0)

Related Questions