使用axios从我的React本机应用程序向我的laravel API发送图片

时间:2018-06-23 21:29:21

标签: laravel react-native axios

我想从我的本地应用程序向我的laravel后端发送图片,因为那是获取图片URI并使用带有其他字符串数据的axios发送图片对象,但发布请求失败。知道当我发送不带图片的发帖请求时,一切正常。

编辑:我已经注释了我的laravel函数的if语句上的所有代码,并将其更改为对$ picture变量的简单影响: $ picture =“ picture”,但未添加产品!这意味着当我提供图片时,甚至没有从我的React应用发送请求。

我的本​​机功能:

    const config = { headers: { "Content-Type": "multipart/form-data" } };
    // appending some string data ...
    data.append("position", JSON.stringify(position));
    // checking if the user took a picture ..
    if (this.state.uri !== null) {
      let filename = this.state.uri.split("/").pop();
      data.append("picture", {
        uri: this.state.uri,
        name: filename,
        type: "image"
      });
    } else {
      data.append("picture", null);
    }
    // sending the request with axios to my backend ..
    const response = axios.post("product/create", data, config);

我的laravel函数:

   $user_id = $this->retrieveIdByToken($request->token);
    $picture = null;
    if ($request->hasFile("picture")){
        $picture = $request->file("picture")->getFilename() . "_" . $user_id . "." . $request->file("picture")->extension();
        Storage::putFileAs(
            '/public/products/pictures/', $request->file('picture'),$picture
        );
    }
    $product = Product::create([
        'user_id' => $user_id,
        'price' => $request->price,
        'position' => json_decode(json_encode($request->position)),
        'category_id' => $request->category_id,
        'name' => $request->name,
        'description' => $request->description,
        'caracteristics' => json_decode(json_encode($request->caracteristics)),
        'image' => $picture
        ]);

2 个答案:

答案 0 :(得分:1)

使用RNFetchBlob库。

工作原理

使用图像选择器并将图像保存为状态,然后使用此代码 10.0.3.2用于genymotion,如果使用真实设备,请替换

extension UILabel {
    var isTruncated: Bool {
        layoutIfNeeded()

        let rectBounds = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)
        var fullTextHeight: CGFloat?

        if attributedText != nil {
            fullTextHeight = attributedText?.boundingRect(with: rectBounds, options: .usesLineFragmentOrigin, context: nil).size.height
        } else {
            fullTextHeight = text?.boundingRect(with: rectBounds, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil).size.height
        }

        return (fullTextHeight ?? 0) > bounds.size.height
    }
}

在Laravel中, 您的API,

 RNFetchBlob.fetch('POST', 'http://10.0.3.2:8000/api/uploadImage', {
    Authorization : "Bearer access-token",
    otherHeader : "foo",
    'Content-Type' : 'multipart/form-data',
    'Accept':'application/json',
  }, [
     { name : 'image1', filename : 'avatar.png', data: this.state.image1},
    ]).then((response) => response.json())
  .then((responseJson) => {

    alert(JSON.stringify(responseJson));

  }).catch((err) => {
    alert(err)
  })

您的控制器

Route::post('upload','ReactController@save');

答案 1 :(得分:0)

我找到了解决方案,首先我不需要给axios一个配置,第二个是大多数类型是image / jpeg