简体   繁体   English

如何在React Native中使用图像uri删除图像?

[英]How to delete image with image uri in React Native?

I am trying to develop a simple app.This app posts a multipart form data with image and some text field. 我正在尝试开发一个简单的应用程序。此应用程序发布包含图像和一些文本字段的多部分表单数据。 I am picking the image using react-native-image-picker. 我正在使用react-native-image-picker选择图像。 My App works fine. 我的应用程序运行正常。 But i noticed it is not clearing the images. 但是我注意到它没有清除图像。 That is why the size of my app is increasing. 这就是为什么我的应用程序大小不断增加的原因。 If i go to General>Iphone storage, i can see my app size increasing. 如果转到常规> iPhone存储,我可以看到我的应用程序大小增加。

I have tried the following code to delete the image but it did not work. 我已尝试使用以下代码删除图像,但无法正常工作。

import RNFetchBlob from 'react-native-fetch-blob';
RNFetchBlob.fs.unlink(imageuri)
 .then(() => {
    console.log('file deleted!');
 });

I think RnFetchBlob needs the actual file path.The code of my upload function is given below. 我认为RnFetchBlob需要实际的文件路径。我的上载函数的代码如下。

upload() {
var new_state = this.state;
var image_array = this.state.imageArray;
var comment = this.state.main_comment;

var new_state = this.state;
new_state.loader_show = !new_state.loader_show;
this.setState(new_state);

navigator.geolocation.getCurrentPosition(position => {
  var lat = parseFloat(position.coords.latitude);
  var lon = parseFloat(position.coords.longitude);
  var new_state = this.state;
  new_state.lat = lat;
  new_state.lon = lon;
});
var position = "position(" + this.state.lat + "," + this.state.lon + ")";

for (var i = 0; i < image_array.length; i++) {
  var file_name = position + "-" + i;
  const data = new FormData();
  data.append("name", file_name);
  data.append("comment", comment); // you can append anyone.
  data.append("images", {
    uri: image_array[i].uri,
    type: "image/jpeg", // or photo.type
    name: "testPhotoName"
  });
  fetch("#####", {
    method: "post",
    body: data
  })
    .then(res => {
      alert("Successfully uploaded from " + position);

      ************************* Here I want to Delete the file *******
      RNFetchBlob.fs.unlink(image_array[i].uri).then(() => {
        console.log("file deleted!");
      });
      ****************************************************************
    })
    .catch(err => {
      // ...
      alert(err);
    });
}

Please be informed that i store the image uri in my state. 请注意,我将图像uri存储在我的状态中。 I dont have the Local file path.I want to delete the image using the uri after the upload is done. 我没有本地文件路径。我想在上传完成后使用uri删除图片。

I solved my problem. 我解决了我的问题。 The below code worked for me. 下面的代码为我工作。

  var uri = images[i].uri;
  var path = uri.split("///").pop();

  RNFetchBlob.fs
    .unlink(path)
    .then(() => {
      alert("File deleted");
    })
    .catch(err => {
      alert(err);
    }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM