Last active
September 11, 2023 17:46
-
-
Save Akiyamka/56ff60d6fd39de5b4fda9730093b962b to your computer and use it in GitHub Desktop.
Wordpress endpoint for upload file to s3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
const TARGET_CONTAINER = '.upload-input-target'; | |
const ERROR_MESSAGE_ID = 'upload-error-message'; | |
const FILE_INPUT_ID = 'resume-input'; | |
const UPLOAD_ENDPOINT = 'https://example.com/wp-json/api/upload'; | |
const ERROR_CLASS = 'error'; | |
const LOADING_CLASS = 'loading'; | |
const LABEL_TEXT = 'Upload' | |
const FALLBACK_ERROR_MESSAGE = 'Something wrong. Please use Intercom for contact with us'; | |
const targetEl = document.querySelector(TARGET_CONTAINER); | |
if (!targetEl) { | |
console.warn('Input container missing'); | |
return; | |
} | |
const setLoading = (isLoading) => | |
isLoading | |
? targetEl.classList.add(LOADING_CLASS) | |
: targetEl.classList.remove(LOADING_CLASS); | |
const linkInputEl = targetEl.querySelector('input'); | |
if (!linkInputEl) { | |
console.warn('Input missing'); | |
return; | |
} | |
const saveLink = (link) => { | |
linkInputEl.value = link; | |
}; | |
const errorMessageEl = document.createElement('div'); | |
errorMessageEl.id = ERROR_MESSAGE_ID; | |
const setErrorMessage = (e) => { | |
errorMessageEl.innerHTML = e; | |
errorMessageEl.hidden = false; | |
targetEl.classList.add(ERROR_CLASS); | |
}; | |
const removeErrorMessage = () => { | |
targetEl.classList.remove(ERROR_CLASS); | |
errorMessageEl.hidden = true; | |
while (errorMessageEl.firstChild) { | |
errorMessageEl.removeChild(errorMessageEl.firstChild); | |
} | |
}; | |
const fileInputEl = document.createElement('input'); | |
fileInputEl.id = FILE_INPUT_ID; | |
fileInputEl.type = 'file'; | |
fileInputEl.hidden = true; | |
const labelInputEl = document.createElement('label'); | |
labelInputEl.setAttribute('for', fileInputEl.id); | |
labelInputEl.innerText = LABEL_TEXT; | |
class ValidationError extends Error {} | |
fileInputEl.addEventListener('change', function(e) { | |
removeErrorMessage(); | |
const data = new FormData(); | |
if (this.files === null) return; | |
if (this.files[0] === undefined) return; | |
data.append('file', this.files[0]); | |
setLoading(true); | |
fetch(UPLOAD_ENDPOINT, { | |
method: 'POST', | |
body: data, | |
}) | |
.then((r) => Promise.all([r.ok, r.json()])) | |
.then(([ok, json]) => { | |
if (ok) saveLink(json.ObjectURL); | |
else throw new ValidationError(json.message) | |
}) | |
.catch((e) => { | |
e instanceof ValidationError ? | |
setErrorMessage(e.message) : | |
setErrorMessage(FALLBACK_ERROR_MESSAGE) | |
}) | |
.finally(() => setLoading(false)); | |
}); | |
targetEl.appendChild(fileInputEl); | |
targetEl.appendChild(labelInputEl); | |
targetEl.appendChild(errorMessageEl); | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// cd http_public | |
// curl -sS https://getcomposer.org/installer | php | |
// php composer.phar require aws/aws-sdk-php | |
require $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'; | |
use Aws\S3\S3Client; | |
// Amazon S3 API settings | |
$bucket = 'YOUR_BUCKET'; | |
$s3 = new S3Client([ | |
'version' => 'latest', | |
'region' => 'YOUR_REGION', | |
'credentials' => [ | |
'key' => 'YOUR_KEY', | |
'secret' => 'YOUR_SECRET', | |
] | |
]); | |
// Add rule to router | |
// https://example.com/wp-json/api/upload | |
add_action('rest_api_init', function () { | |
register_rest_route('api', '/upload', | |
array( | |
'methods' => 'POST', | |
'callback' => 'uploadFile', | |
) | |
); | |
}); | |
function uploadFile($request) { | |
global $s3, $bucket; | |
$params = $request->get_file_params(); | |
// File to upload | |
$file = $params["file"]; | |
$file_name = uniqid('YOUR_NAMESPACE-', true) . '-' . basename($file["name"]); | |
$file_type = pathinfo($file_name, PATHINFO_EXTENSION); | |
$allowed_types = ["pdf", "doc", "docx", "txt", "rtf"]; | |
if (!in_array($file_type, $allowed_types)) { | |
return new WP_Error("wrong_type", "File type not allowed ({$file_type})", [ | |
"status" => 400, | |
]); | |
} | |
try { | |
$file_temp_src = $file["tmp_name"]; | |
$result = $s3->putObject([ | |
"Bucket" => $bucket, | |
"Key" => $file_name, | |
"ACL" => "public-read", | |
"SourceFile" => $file_temp_src, | |
]); | |
$result_arr = $result->toArray(); | |
if (!empty($result_arr["ObjectURL"])) { | |
return $result_arr; | |
} else { | |
return new WP_Error("url_missing", "Upload failed", [ | |
"status" => 500, | |
]); | |
} | |
} catch (Exception | Aws\S3\Exception\S3Exception $e) { | |
debug_log($e); | |
return new WP_Error( | |
"storage_servise_error", | |
($api_error = $e->getMessage()), | |
["status" => 500] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment