允许通过GraphQL为Elixir后端上传多部分内容(图片)

问题描述 投票:1回答:1

我希望能更清楚地了解我可能在哪里出错。抱歉,我问了很多问题,因为我感到有点迷茫,被这个问题困扰了大约一个星期。

[当前,我已经更改了用于与apollo-client链接的软件包。以前的软件包是apollo-link-http,现在我使用的是apollo-absinthe-upload-link,因为我阅读了它后可以上传图片。

完成如下

const httpLink = createLink({
    uri: 'http://localhost:4000/api',
    credentials: 'same-origin',
    fetch,
    fetchOptions
});

向后端发送信息没有任何变化,但是在上传图像方面,我确实仍然迷失了方向。该图像的目的是上传到云,然后将url信息与产品详细信息一起保存。

我正在使用一个钩子作为const [ images, setImages ] = useState([]);和一个输入<input type="file" placeholder="Upload Image" onChange={handleUploadImage} />

onChange函数的目的是将图像信息设置为images属性。当我们将变异发送到后端时,其完成方式如下

const buildForm = () => {
    let storeID = 2;
    const fileData = fileList.fileList.map((file) => {
        return file.originFileObj;
    });
    const data = new FormData();
    data.append('fileData', images);
    debugger;
    return {
        productName,
        productDescription,
        productPrice,
        productType,
        isReturnable,
        storeID,
        fileData: data
    };
};

当它出现时,在我的控制台中,我得到一个错误Uncaught (in promise) Error: GraphQL error: Argument "fileData" has invalid value $fileData.,并且我在后端看到键fileData的值为空对象。我希望就什么可能是错误的或应该考虑的问题获得一些建议。如果有人提到CURL,请解释一下,因为我不知道这对GraphQL和发送突变是什么意思。谢谢您对此事的帮助。

PS-正在使用的突变电话是

export const CREATE_PRODUCT_MUTATION = gql`
    mutation CreateProduct(
        $storeID: Int!
        $productName: String!
        $productDescription: String!
        $productPrice: Decimal!
        $productType: Int!
        $isReturnable: Boolean!
        $fileData: Upload!
    ) {
        createProduct(
            product: {
                productName: $productName
                productDescription: $productDescription
                productPrice: $productPrice
                productType: $productType
                isReturnable: $isReturnable
            }
            storeId: $storeID
            fileData: $fileData
        ) {
            id
            productName
            productDescription
            productPrice
        }
    }
`;

更新-网络返回请求

{"errors":[{"locations":[{"column":0,"line":2}],"message":"Argument \"fileData\" has invalid value $fileData."}]}

后端架构

@desc "List a new product"
field :create_product, :product do
  arg(:product, :new_product)
  arg(:store_id, :integer)
  arg(:file_data, non_null(:upload))
reactjs graphql elixir phoenix-framework absinthe
1个回答
0
投票

[apollo-absinthe-upload-link期望使用类型为FileBlobsee here)的变量,但是您将fileData作为类型FormData传递。

由于您的input类型是file,因此您可以这样做:

const handleUploadImage = (event) => setImages(event.target.files);

const buildForm = () => ({
  productName,
  productDescription,
  productPrice,
  productType,
  isReturnable,
  storeID: 2,
  fileData: images[0],
});

参考:

file-selector

react-dropzone

© www.soinside.com 2019 - 2024. All rights reserved.