Giter Site home page Giter Site logo

dre1080 / wp-graphql-upload Goto Github PK

View Code? Open in Web Editor NEW
32.0 32.0 3.0 68 KB

Upload support and functionality for WPGraphQL as specified by graphql-multipart-request-spec.

License: GNU General Public License v3.0

Shell 26.68% PHP 73.32%
graphql graphql-upload upload wordpress wordpress-plugin wp-plugin wpgraphql wpgraphql-plugin

wp-graphql-upload's People

Contributors

dre1080 avatar justlevine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

wp-graphql-upload's Issues

Trouble getting the basic example to work

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?

Error:Expected type Upload; Could not get uploaded file.

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.

  • I am using nextjs and apollo.

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).

  • Just the file (image is e.taget.values[0])
 const onFileUpload = () => {
    uploadMediaItem({
      variables: {
        file: image
      }
    })
  };
  • With formData:
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!

How does multiple upload work?

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.

CleanShot 2022-08-17 at 14 49 56@2x

CleanShot 2022-08-17 at 14 50 47@2x

Thank you.

[ApolloError: Internal server error]

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]

php 8 support

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."

Hire for Troubleshooting

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?

Wpgraphql upload file

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?

Cant move uploaded files.

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'];
  
  }

}

Release WPGraphQL Upload to packagist

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:

  1. manually download and install the zip file on the WP backend,
  2. add configure this repo in composer.repositories[], or
  3. Pipe the release url to wp 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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.