【问题标题】:React native upload image or file via php通过php反应本机上传图像或文件
【发布时间】:2022-02-02 19:23:31
【问题描述】:

我正在使用文档选择器通过 php 上传图片。

这是我的 js 代码:


const [singleFile, setSingleFile] = useState(null);

  const uploadImage = async () => {
    
    // Check if any file is selected or not
    if (singleFile != null) {
      
      // If file selected then create FormData
      const fileToUpload = singleFile;
      const data = new FormData();
      data.append('name', 'imgup');
      data.append('attachement_file', fileToUpload);
      
      axios.post(''+ALL.API_URL+'/sellwithus/upload.php', data, {
        headers: {
          'Content-Type': 'multipart/form-data; ',
        }
      })
      .then((response) => {
        console.log(response);
      })

    } else {
      // If no file selected the show alert
      alert('Please Select File first');
    }
  };


选择代码:


  const selectFile = async () => {
    // Opening Document Picker to select one file
    try {
      const res = await DocumentPicker.pick({
        // Provide which type of file you want user to pick
        type: [DocumentPicker.types.images],
        // There can me more options as well
        // DocumentPicker.types.allFiles
        // DocumentPicker.types.images
        // DocumentPicker.types.plainText
        // DocumentPicker.types.audio
        // DocumentPicker.types.pdf
      });
      // Printing the log realted to the file
      console.log('res : ' + JSON.stringify(res));
      // Setting the state to show single file attributes
      setSingleFile(res);
    } catch (err) {
      setSingleFile(null);
      // Handling any exception (If any)
      if (DocumentPicker.isCancel(err)) {
        // If user canceled the document selection
        alert('Canceled');
      } else {
        // For Unknown Error
        alert('Unknown Error: ' + JSON.stringify(err));
        throw err;
      }
    }
  };

这是 res 结果:

console.log(JSON.stringify(res));

res :[{"size":1454366,"fileCopyUri":null,"name":"D0BED0E3-4567-41DA-9B21-8C409E355A87.JPG","uri":"file:///Users/saeedmatar/Library/Developer /CoreSimulator/Devices/098A7371-530E-4667-AAAF-80EAE97F9A9E/data/Containers/Data/Application/06A2878B-D812-4B3C-BEF0-2E40DBFE9A27/tmp/org.reactjs.native.example.JelApp-Inbox/D0BED0E3-4567 -41DA-9B21-8C409E355A87.JPG"}]

这是我的 php 代码:

$_POST = json_decode(file_get_contents("php://input"),true);

$imageData=$_POST["_parts"][1][1][0];

file_put_contents('uploads/image.JPG', $imageData["uri"]);

上传的图片为 0 mb 且未显示。

如何使用 uri 上传图片?

【问题讨论】:

标签: php reactjs react-native


【解决方案1】:

react-native-document-picker返回的文件uri是设备应用本地缓存中的引用,不能用于上传数据。

获取并上传文档 BLOB 数据。


 const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", [DOCUMENT_PATH_URI_HERE], true);
    xhr.send(null);
  });

// code to submit blob data


// We're done with the blob, close and release it
  blob.close();


【讨论】:

  • 感谢您的回答。我使用的是 document.picker 而不是图像选择器。 github.com/rnmods/…我应该在我的代码中更改什么以匹配您的答案?
  • 对不起,我更新了答案
  • 感谢您更新答案。我照你说的做了。我把 fileToUpload[0].uri 像:xhr.open("GET", fileToUpload[0].uri, true); console.log(blob)= {“_data”:{“__collector”:{},“blobId”:“86D1C8F3-B32E-48EA-AC31-C265571F628D”,“名称”:“D0BED0E3-4567-41DA-9B21-8C409E355A87 .JPG", "offset": 0, "size": 1454366, "type": "application/octet-stream"}}。那么我应该在 php 中做什么?
  • 这是我的 axios: axios.post(''+ALL.API_URL+'/sellwithus/upload.php', blob, { headers: { 'Content-Type': 'multipart/form-data ; ', } }) .then((response) => { console.log(response); })
  • 我不知道您的 PHP 后端如何处理 BLOB 数据,我使用 Amazon S3 或 Firebase Storage 等云对象托管提供商测试了此解决方案
猜你喜欢
  • 1970-01-01
  • 2019-02-05
  • 2018-08-26
  • 2012-11-24
  • 2017-03-27
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多