php wp base 64上传文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php wp base 64上传文件相关的知识,希望对你有一定的参考价值。

/**
    * Upload file
    */
    private static function upload_user_file() {
    	if(!woptima_isset_notempty([$_POST["filename"],$_POST["image"],$_POST["mime"],$_POST["user_id"]])) {
    		condomini_remote_log(300, "Errore dati imamgine");
    		echo json_resp(300, "Errore dati imamgine");
    		die();
    	}

    	$filename 		= $_POST["filename"];
    	$nicename 		= str_replace(["-","_"], " ", pathinfo($filename, PATHINFO_FILENAME));
    	$decoded 		= base64_decode($_POST["image"]);
    	$mime 			= $_POST["mime"];
    	$user_id 		= $_POST["user_id"];
	    $upload_dir 	= wp_upload_dir();
		$upload_path 	= str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;

		$image_upload 	= file_put_contents( $upload_path.$filename, $decoded );

		if( !function_exists( 'wp_handle_sideload' ) ) {
		 	require_once( ABSPATH . 'wp-admin/includes/file.php' );
		}

		if( !function_exists( 'wp_get_current_user' ) ) {
		 	require_once( ABSPATH . 'wp-includes/pluggable.php' );
		}

		if ( ! function_exists( 'wp_crop_image' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/image.php' );
		}

		$file             = array();
		$file['error']    = '';
		$file['tmp_name'] = $upload_path . $filename;
		$file['name']     = $filename;
		$file['type']     = $mime;
		$file['size']     = filesize( $upload_path . $filename );

		$file_return = wp_handle_sideload( $file, array( 'test_form' => false ) );
		$newfilename = $file_return['file'];

		$attachment = array(
		 'post_mime_type' 	=> $file_return['type'],
		 'post_content' 	=> '',
		 'post_status' 		=> 'inherit',
		 'post_author' 		=> $user_id,
		 'guid' 			=> $upload_dir['url'] . '/' . basename($newfilename),
		 'post_title' 		=> $nicename
		 );

		if($uploaded_file = wp_insert_attachment( $attachment, $newfilename )) {
			wp_update_post(['ID' => $uploaded_file, 'post_title' => $nicename]);

			$attach_data = wp_generate_attachment_metadata( $uploaded_file, $newfilename );
			wp_update_attachment_metadata( $uploaded_file, $attach_data );

			$filedata 		= get_post($uploaded_file);
			$img_parts		= pathinfo($filedata->guid);
			$icon 			= $img_parts["dirname"].$img_parts["filename"]."-100x100.".$img_parts["extension"];
			$filedata->icon = $icon;

			condomini_remote_log(200, "Success", $filedata);
    		echo json_resp(200, "Success", $filedata);
        	die();
		} else {
			condomini_remote_log(300, "Error uploading file");
			echo json_resp(300, "Error uploading file");
			die();
		}
	}

以上是关于php wp base 64上传文件的主要内容,如果未能解决你的问题,请参考以下文章

php图像文件上传并转换为base64而不保存图像

php 将base64编码文件上传到Wordpress

请不要用php进行base64编码文件上传

通过 wp_handle_upload 删除未放入上传文件夹的图像

PHP base64_decode+gzinflate压缩和解密代码图文教程

php 上传Image Base64