Remove an image that was not put in uploads folder via wp_handle_upload

前端 未结 3 1155
长情又很酷
长情又很酷 2021-02-20 05:48

I\'m saving an image to uploads folder, but I\'m using file_put_contents instead of wp_handle_upload - because I get an image in base64 and not as a file in $_FILES.

Im

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-20 06:14

    as @KamilP said, WP inserts records in wp_posts and wp_postmeta tables.

    So first you have to save your base64 images in temporary directory, then by using it's relative path and other data you can insert record in database by using wp_insert_attachment, link contains appropriate example. This function will add image to media library.

    To generate more thumbnails you can use wp_generate_attachment_metadata function. This function will update wp_postmeta table also with all details of image and thumbnails.

    After this you can use wp_delete_attachment function to delete image from directory and database as well.

    Another solution:

    • Use function from this link to generate image from base64 string.
    • then get mime type, size and path of image
    • create an array similar to $_FILES's.
    • then pass it to wp_handle_upload

    UPDATE :

    $_FILES array's structure is like this

    array(5) {
        'name'     => string(8) "file name.extension" // file name with extension
        'type'     => string(0) "" // mime type of file, i.e. image/png
        'tmp_name' => string(0) "" // absolute path of file on disk.
        'error'    => int(2) // 0 for no error
        'size'     => int(0) // size in bytes
      }
    

    You can create array like above with all details, use various file handling PHP functions to get size and mime type. Name is whatever you want to put, and tmp_name is a path of file on server where file is exists, in your case location of folder where you save your file from base64 string.

    See updated link above for function which will give you image from base64 string.

提交回复
热议问题