https://github.com/blueimp/jQuery-File-Upload/issues/2924
<input id="inputFileToLoad" type="file" onchange="encodeImageFileAsURL();" />
<div id="imgTest"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type='text/javascript'>
function encodeImageFileAsURL() {
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
var srcData = null;
fileReader.onload = function(fileLoadedEvent) {
var srcData = fileLoadedEvent.target.result; // <--- data: base64
var newImage = document.createElement('img');
newImage.src = srcData;
document.getElementById("imgTest").innerHTML = newImage.outerHTML;
// alert("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
console.log("Converted Base64 version is " + document.getElementById("imgTest").innerHTML);
request = $.ajax({
url: '/import_file/base64-api2.php',
type: 'POST',
// dataType: 'json',
// encode: true,
async: false,
// contentType: 'application/json',
// processData: false,
// contentType: false,
data: {"media":srcData}
// data: JSON.stringify({})
});
}
fileReader.readAsDataURL(fileToLoad);
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
// $inputs.prop("disabled", false);
});
}
}
</script>
Chunk file for upload.
PHP decode
function base64_to_jpg($base64, $output_file) {
$ext = 'jpeg';
$img = str_replace('data:image/jpeg;base64,', '', $base64);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = "./starbase/" . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
}
Base64 chunked
https://github.com/blueimp/jQuery-File-Upload/issues/1947
jsFiddle alike
http://jsbin.com/piqiqecuxo/1/edit?js,console,output
http://jsfiddle.net/ghinda/fRgbf/
https://github.com/blueimp/jQuery-File-Upload/pull/3052
https://stackoverflow.com/questions/8668449/xmlhttprequest-vs-httprequest
https://github.com/blueimp/jQuery-File-Upload/issues/2606
What I need is preprocess the file be4 send.
Update working example here both blueimp JS + API in PHP.
PHP UploadHandler seem not necessary ?
Fast notes:
- to encode and append base64 file data to POST:
inside fileupload() add: event, add:
try {
async function convertFileToBase64(file) {
let base64Promise = new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file[0]);
console.log('be4 onload');
reader.onload = () => {
data.fileBase64 = reader.result;
resolve(data.fileBase64);
data.submit();
};
reader.onerror = reject;
});
await base64Promise;
}
convertFileToBase64(data.files);
// data.submit();
} catch(err) {
console.log(err);
}
...
To append to formData:
in event chunkbeforesend (add new event if you not added yet). This is for split chunk big file.
chunkbeforesend: function (e, data) {
data.formData = {
'folderId': id_folder_selected,
'uniqueFileName': uniqueFileName,
'fileBase64': data.fileBase64,
'fileType': data.files[0].type,
'fileSize': data.files[0].size,
'fileName': data.files[0].name
};
},
...
In case only 1 part (small file or not enable config split file):
add bind() method
fileupload(...).bind():
.bind('fileuploadsubmit', function (e, data) {
// console.log(data.files);
data.formData = {
'folderId': id_folder_selected,
'fileBase64': data.fileBase64,
'fileType': data.files[0].type,
'fileSize': data.files[0].size,
'fileName': data.files[0].name
};
});
Disable file binary send:
inside _initXHRData, section near _isInstanceOf('Blob')...
// Do not send binary file to avoid blocked by CF...
// formData.append(
// ($.type(options.paramName) === 'array' &&
// options.paramName[index]) ||
// paramName,
// file, // file | null
// fileName
// );
Do not send file in binary to avoid firewall scan for example SQLi BODY, in AWS WAF it scan first 8KB of body data (can be setting to more).
Server side (PHP), it seem we do not need UploadHandle.php or with simple server side handle (no image crop, resize...) => we can implement simple API to save base64 file. Be careful with another stuff like you have to escape filename yourself...
public function base64Decode($base64, $type='')
{
if (empty($base64) || empty($type)) {
return false;
}
$typeUrl = 'data:'. $type . ';base64,';
$data = str_replace($typeUrl, '', $base64);
$data = str_replace(' ', '+', $data);
return base64_decode($data);
}
private function saveUploadedFile($data, $fileName, $path='')
{
$filePath = !empty($path) ? $fileName : $path . '/'. $fileName;
$success = file_put_contents($filePath, $data);
return $success;
}
My code is lack of clean & refactoring so you should refactor yourself.
Don't know why merging chunk file on server side work without any change. Normally I have to using Content-Range header to merge programmatically.
https://github.com/puppeteer/puppeteer/issues/1599
Resource buffer size may be an issue when using base64 ?
At least when debug data sent in Dev Tool.
https://stackoverflow.com/questions/27254735/filereader-onload-with-result-and-parameter
https://www.tabnine.com/code/javascript/functions/builtins/FileReader/onloadend
https://groups.google.com/a/dartlang.org/g/misc/c/-_89QH4IMU4
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/loadend_event
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
https://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue
https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript?rq=1
PHP base64_decode()
base64_decode(string $string, bool $strict = false): string|false
strict
If the strict parameter is set to true then the base64_decode() function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.
To check base64 data, use crc32() check sum for verify same data.
ReplyDeleteCroydon Cars MiniCab Service in London UK,Choose our Minicab
for a quick trip and safely to get to the Gatwick Airport,
Heathrow Airportalso offers some services to minicab drivers
who are not associated with itin the area of Croydon and in
other towns.We are offer Low Fair for Airport Transfers from
Croydon everyday such as ✓Croydon Minicabs ✓Shirley Minicabs
✓Waddon Minicabsand etc.We want to welcome you to our new
corporate website:www.croydoncar.co.uk/
ReplyDeleteAirport Transfer service from City Airport Taxis. Book your private airport transfers online, for a reliable transportation service at competitive, all inclusive prices.
www.croydoncar.co.uk/