dre1080 / wp-graphql-upload Goto Github PK
View Code? Open in Web Editor NEWUpload support and functionality for WPGraphQL as specified by graphql-multipart-request-spec.
License: GNU General Public License v3.0
Upload support and functionality for WPGraphQL as specified by graphql-multipart-request-spec.
License: GNU General Public License v3.0
Hi there. I followed the readme and I am getting an internal server error on upload. Do you have a working example in React of how to send a file to the mutation?
HI!
Sorry for opening an issue, didn't know the best way to contact!
I am new to the wordress world and wpgraphql and was trying to use this package but seems I don't manage to make it work, hopefully you can help me understand it.
This is the error I get: "Variable "$file" got invalid value []; Expected type Upload; Could not get uploaded file, be sure to conform to GraphQL multipart request specification. Instead got: []
I am just getting the file from the input type="file" and sending it on the request (also tried to create a formData with it but no success).
const onFileUpload = () => {
uploadMediaItem({
variables: {
file: image
}
})
};
const onFileUpload = () => {
const formData = new FormData();
formData.append(
"myFile",
image,
image.name
);
uploadMediaItem({
variables: {
file: formData
}
})
};
And the query on my client side:
const UPLOAD = gql`
mutation UploadWpGraphql(
$file: Upload!,
) {
upload(input:{
file: $file
}){
text
}
}
Thanks!
Hello,
Thank you very much for your plugin. Saved lives in file uploads.
But I have a problem, I cannot upload multiple files.
First, I made my species definition. There is no problem in single installation, but the field named "attachments" must be multiple.
I am sharing the screenshots below, I would be very happy if you could help.
Thank you.
hi, every time i try to upload a simple jpg or png image I get the following error message:
error 500 This file type is not permitted for security reasons
I have made it like this, this is not an error but I also do not understand, if the issue is my setup or the problem with wp-graphql-upload.
Can you please review it?
thanks
register_graphql_mutation('uploadProfilePicture', [
'inputFields' => [
'file' => [
'type' => 'Upload',
],
],
'outputFields' => [
'avatarUrl' => [
'type' => 'String',
'resolve' => function ($payload) {
return $payload['avatarUrl'];
}
],
'avatarUrlThumbnail' => [
'type' => 'String',
'resolve' => function ($payload) {
return $payload['avatarUrlThumbnail'];
}
],
'successMessage' => [
'type' => 'Boolean',
'resolve' => function ($payload) {
return $payload['successMessage'];
}
]
],
'mutateAndGetPayload' => function ($input, $context, $info) {
if (!function_exists('wp_handle_sideload')) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$file_return = wp_handle_sideload($input['file'], [
'test_form' => false,
'test_type' => false,
]);
if (isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
throw new \GraphQL\Error\UserError("The file could not be uploaded.");
}
$filename = $file_return['file'];
$attachment = [
'guid' => $file_return['url'],
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
];
$attachment_id = wp_insert_attachment($attachment, $filename);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attachment_id, $filename);
wp_update_attachment_metadata($attachment_id, $attach_data);
update_field('profile_pic', $attachment_id, 'user_' . $current_user->ID);
$profile_pic = get_field('profile_pic', 'user_' . $current_user->ID);
$avatarUrl = $profile_pic['url'];
$avatarUrlThumbnail = $profile_pic['sizes']['thumbnail'];
return [
'avatarUrl' => $avatarUrl,
'avatarUrlThumbnail' => $avatarUrlThumbnail,
'successMessage' => true,
];
}
]);
Uploading it this way:
const UPLOAD_IMAGE_MUTATION = gql`
mutation UploadProfilePicture($input: UploadProfilePictureInput!) {
uploadProfilePicture(input: $input) {
avatarUrl
avatarUrlThumbnail
}
}
`;
const selectImage = async () => {
// Check for the permission
const permissionResult =
await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("You've refused to allow this app to access your photos!");
return;
}
// Open the image picker
let pickerResult = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true, // or false based on your requirement
aspect: [4, 3], // aspect ratio
quality: 1, // quality of the image
});
if (pickerResult.canceled === true) {
return;
}
// Access the selected asset
const selectedAsset = pickerResult.assets[0]; // Assuming single image selection
if (selectedAsset) {
const source = {
uri: selectedAsset.uri,
type: selectedAsset.type, // type is now part of the asset
name: selectedAsset.fileName || "profile-pic.jpg", // name can be accessed or set a default
};
console.log(source);
uploadImage(source);
} else {
console.error("No image selected");
}
};
const [uploadProfilePicture] = useMutation(UPLOAD_IMAGE_MUTATION);
const uploadImage = async (imageFile) => {
// Convert image file to a format suitable for GraphQL upload
let localUri = imageFile.uri;
let filename = localUri.split("/").pop();
// Infer the type of the image
let match = /\.(\w+)$/.exec(filename);
let type = match ? `image/${match[1]}` : imageFile.type;
// Prepare the formData
const formData = new FormData();
formData.append("file", { uri: localUri, name: filename, type });
console.log("Form Data Prepared:", formData);
try {
console.log("Sending request to server");
const response = await uploadProfilePicture({
variables: {
input: { file: imageFile }, // Modify here to match the GraphQL mutation
},
});
console.log("Response received:", response);
// Extract the data from the response
const { avatarUrl, avatarUrlThumbnail, successMessage } =
response.data.uploadProfilePicture;
if (successMessage) {
console.log(successMessage); // Log or handle the success message as needed
// Update user context with new image URLs
setUserData({ avatarUrl, avatarUrlThumbnail });
}
} catch (error) {
console.error("Error during image upload:", error);
console.error("Error details:", error.networkError?.result || error);
}
};
The problem is am still getting this error:
ERROR Error during image upload: [ApolloError: Internal server error]
ERROR Error details: [ApolloError: Internal server error]
hi, my composer complains when i use php 8
dre1080/wp-graphql-upload v0.1.2 requires php ^7 -> your php version (8.0.13) does not satisfy that requirement."
Hey Dre,
We are looking for help troubleshooting the previously reported file & folder permissions issue. Can we hire you for a few hours of consulting/troubleshooting?
Hello,
Nice to meet you!
I want to upload file from computer to website via by graphql. Can you show me how to use your plugin?
I cant move the uploaded files once they are on the server. The file appears in \tmp
, and the destination file has the correct permissions. Any ideas?
E.g.
public function mutate_and_get_payload() : callable {
return function( $input, AppContext $context, ResolveInfo $info ) : array {
$file = get_file_upload_value( $input); // returns if FileUpload value was passed to the mutation, or throws execption.
$target = get_my_target_path();
if ( ! is_writable( $dirname( $target['path'] ) ) {
throw new UserError( 'Failed permission message' );
}
if ( ! file_exists( $file['tmp_name'] ) {
throw new UserError( 'File doesnt exist on server message' );
}
// This execption gets thrown!!!!!
if( ! move_file_upload( $file['tmp_name'], $target['path'] ) {
/// @todo delete tmp upload.
throw new UserError( ' Could not move file ');
}
return $target['url'];
}
}
Considering the reliance on dependency management in the headless world, it would would be really helpful to be able to run composer require dre1080/wp-graphql-upload
in order to install the plugin.
Currently you either need to:
composer.repositories[]
, orwp cli
.None of these are particularly friendly, and only the second one provides users with version update notifications.
Nowadays, adding a repo to packagist is easy and automatic with an official Github Hook, so once set up no additional maintainer work is required.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.