Skip to content

Instantly share code, notes, and snippets.

@alexandrebodin
Created January 23, 2020 20:46
Show Gist options
  • Save alexandrebodin/4f658155290360325ff1c96c0be22b94 to your computer and use it in GitHub Desktop.
Save alexandrebodin/4f658155290360325ff1c96c0be22b94 to your computer and use it in GitHub Desktop.
Strapi graphQL upload mutation
import React from "react";
import "./App.css";
import { ApolloProvider } from "@apollo/react-hooks";
import gql from "graphql-tag";
import { ApolloClient } from "apollo-client";
import { createUploadLink } from "apollo-upload-client";
import { InMemoryCache } from "apollo-cache-inmemory";
const cache = new InMemoryCache();
const client = new ApolloClient({
cache,
link: createUploadLink({
uri: "http://localhost:1337/graphql"
})
});
const UPLOAD = gql`
mutation($file: Upload!) {
upload(file: $file) {
name
}
}
`;
class App extends React.Component {
state = {
image: null
};
onImageChange = event => {
console.log(event.target.files);
this.setState({
image: event.target.files[0]
});
};
onSubmit = e => {
e.preventDefault();
console.log(this.state.image);
client
.mutate({
mutation: UPLOAD,
variables: {
file: this.state.image
}
})
.then(res => {
console.log(res);
})
.catch(err => {
console.error(err);
});
};
render() {
return (
<ApolloProvider client={client}>
<form onSubmit={this.onSubmit}>
<input
type="file"
name="files"
onChange={this.onImageChange}
alt="image"
/>
<br />
<button type="submit">Send</button>
</form>
</ApolloProvider>
);
}
}
export default App;
@Aryaman73
Copy link

Are we able to set the "name" of the file, or any other properties? We have "name" in the mutation but we aren't setting or getting it.

@Arshiash80
Copy link

@Aryaman73 You've probably already found an answer to your question. I'm sharing this in the hope that it will be helpful to others as well:

mutation Upload(
  $refId: ID
  $ref: String
  $field: String
  $info: FileInfoInput
  $file: Upload!
) {
  upload(refId: $refId, ref: $ref, field: $field, info: $info, file: $file) {
    data {
      id
      attributes {
        hash
        name
      }
    }
  }
}

example:

{
    file: blob, // Blob or File
    refId: userId, // In my case the user-permissions.user's id
    ref: "plugin::users-permissions.user", 
    field: "avatar", // Media field at user-permissions.user
    info: {
      name: `${userId}-avatar`,
      alternativeText: ``,
      caption: ``,
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment