How can javascript upload a blob?
You can use the FormData API.
If you're using jquery.ajax
, you need to set processData: false
and contentType: false
.
var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('data', soundBlob);
$.ajax({
type: 'POST',
url: '/upload.php',
data: fd,
processData: false,
contentType: false
}).done(function(data) {
console.log(data);
});
Upload blob with AJAX and move file in the server
You should not use base64 for file upload. With a large file, your base64 will be extremely large. Although base64 is a relatively efficient way of encoding binary data it will, on average still increase the file size by more than 25%. This increases your bandwidth bill and uploads time. Instead, use the form data to upload the file. Just use base64 to preview the file before upload.
You also don't need to implement an XMLHttpRequest yourself (unless you want your code to work in IE :D) use Fetch API instead.
<input id="file-upload" type="file" name="file" onchange="readFile()" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<script>
function readFile() {
if(this.files && this.files[0]) {
const fileReader = new FileReader();
fileReader.addEventListener("load", function(e) {
//you can use base64 to preview file
console.log('Base64:', e.target.result);
});
fileReader.readAsDataURL( this.files[0] );
}
}
function uploadFile() {
const formData = new FormData();
const fileUploadInput = document.getElementById('file-upload');
formData.append("file", fileUploadInput.files[0]);
fetch('/upload.php', {
method: "POST",
body: formData
})
.then(() => {
console.log('Success');
})
.catch(error => {
console.error('Error:', error);
});
}
</script>
In PHP code, you can get the file from a global variable $_FILES
<?php
// upload.php
var_dump($_FILES['file']);
?>
How to upload output blob to a server?
Here is fully working example with how to upload a blob:
<html>
<head>
<meta charset="UTF-8">
<script>
function init() {
var form = document.getElementById('f');
if(form) {
form.addEventListener('submit', function(event) {
if(form.ajax.checked) {
var formData = new FormData();
for(var i=0; i<form.length; i++) {
if(form[i].type == 'file') {
var files = form[i].files;
var blob = files[0].slice(0, files[0].size, files[0].type);
formData.append(form[i].name, blob, files[0].name);
}
else {
formData.append(form[i].name, form[i].value);
}
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
// what do I do here?
// is it
// window.location = URL.createObjectURL(xhr.response);
// or should it be
// document.write(responseText);
// or even
// document.close(); document.open(); document.write(xhr.responseText);
// or?
}
};
xhr.open('POST', form.action, true);
xhr.send(formData);
event.preventDefault();
}
}, false);
}
}
</script>
</head>
<body onload='init()'>
<?php
if(isset($_FILES['file'])) {
echo '<ul>';
echo '<li>name: '.$_FILES['file']['name'].'</li>';
echo '<li>type: '.$_FILES['file']['type'].'</li>';
echo '<li>size: '.$_FILES['file']['size'].'</li>';
echo '<li>upload type: '.$_POST['ajax'].'</li>';
echo '</ul>';
echo "<a href='http://localhost/test.php'>reset</a>";
}
else {
?>
<form enctype='multipart/form-data' id='f' method='POST'>
<input name='file' type='file'/>
ajax: <input name='ajax' type='checkbox'/>
<input type='submit'/>
</form>
<?php
}
?>
</body>
</html>
Convert an image from file upload to blob to post to database VueJS
You need to take the values.image, console.log the response from it so see how the data is structured. There should be a string value in there that you may need to split at .
so that you can take the MIME type of the file that you have uploaded as you need this to create the blob.
The structure of a Blob is like so.
new Blob(blobParts, options);
/**
* blobParts is an array of Blob/BufferSource/String values.
* options: option object:
* type - Blob type, usually MIME-type e.g image/png
* endings - whether to transform end-of-line to make the Blob corrospond to current OS newlines.
*/
You should also be able to turn this into a Blob by calling the .blob()
function on the file that has been uploaded.
A dummy is as so:
// your file name in the second param should be constructed of the string that you have logged and split earlier.
var fileToUpload = new File([Blob], 'some_file_name.jpg', {
type: "image/jpg", // this should be from your string split of the filename to check the file upload type.
lastModified: new Date(),
});
form.append("image", fileToUpload);
Uploading a blob with nodejs
This is very easy to do with the multer module for Express.
We'll also add a test .html file to the directory (client side JavaScript).
To test this out, run node server.js, then navigate to http://localhost:8081 in your browser.
server.js
const express = require('express');
const multer = require('multer');
const upload = multer();
const fs = require('fs');
var app = express();
app.use(express.static(__dirname));
app.post('/post_pdf/', upload.any(), (req, res) => {
console.log('POST /post_pdf/');
console.log('Files: ', req.files);
fs.writeFile(req.files[0].originalname, req.files[0].buffer, (err) => {
if (err) {
console.log('Error: ', err);
res.status(500).send('An error occurred: ' + err.message);
} else {
res.status(200).send('ok');
}
});
});
app.listen(process.env.PORT || 8081);
index.html
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
</script>
</head>
<body>
<input type="file" onchange="loadFile()"><br>
<button onclick="uploadFile()">Upload..</button>
<div id='result'></div>
</body>
</html>
How to upload an image into a folder with blob:http link using PHP and JavaScript?
Hi I have changed just 3 code block that are
if (document.getElementById('imageData').files[0]) {
reader.readAsDataURL(document.getElementById('imageData').files[0]);
}
instead of
var blob = (window.URL || window.webkitURL).createObjectURL(this.files[0]);
document.getElementById('fileURL').value = blob;
and move your ajax request in prview onload event
document.getElementById("avatar-img").onload = function () {
// Upload the selected image automatically into the 'uploads' folder
var filename = "avatar.jpg";
var data = new FormData();
data.append('file', document.getElementById('imageData').files[0]);
$.ajax({
url : "upload.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}, error: function() {
alert("Something went wrong, try again!");
}
});
};
and correct file element use in data.append
data.append('file', document.getElementById('imageData').files[0]);
and you can see complete code block
document.getElementById("imageData").onchange = function () {
var reader = new FileReader();
reader.onload = function (data) {
document.getElementById("avatar-img").src = data.target.result;
console.log(data.target.result);
document.getElementById("avatar-img").onload = function () {
// Upload the selected image automatically into the 'uploads' folder
var filename = "avatar.jpg";
var data = new FormData();
data.append('file', document.getElementById('imageData').files[0]);
$.ajax({
url : "upload.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}, error: function() {
alert("Something went wrong, try again!");
}
});
};
};
if (document.getElementById('imageData').files[0]) {
reader.readAsDataURL(document.getElementById('imageData').files[0]);
}
/*// Read the image file as a data URL.
var blob = (window.URL || window.webkitURL).createObjectURL(this.files[0]);
document.getElementById('fileURL').value = blob;
*/
};
Related Topics
Execute PHP Function With Onclick
Why Is Using Onclick() in HTML a Bad Practice
How to Clear the Canvas For Redrawing
Changing Website Favicon Dynamically
Detecting Input Change in Jquery
Dynamically Set Value of a File Input
JavaScript: How to Find Out If the User Browser Is Chrome
Electron Require() Is Not Defined
Difference Between ≪Script Src="Foo.Js"≫≪/Script≫ and ≪Script Src="Foo.Js"/≫
How to Set Html5 Required Attribute in JavaScript
Load More Posts Ajax Button in Wordpress
Why Don't Self-Closing Script Elements Work
Why Can't I Call a Function Named Clear from an Onclick Attribute
Using an HTML Button to Call a JavaScript Function
Contenteditable, Set Caret At the End of the Text (Cross-Browser)