I have this normal file upload, but what do I need is to send a file stored as a string in local storage along with FormData, because I cannot change anything on server. I will store the file locally using readAsBinaryString or readAsDataURL .
var reader = new FileReader();
/**
File reading code
reader.readAsBinaryString(file);
**/
var fileString = reader.result
I need to send fileString into below formData.append instead of the imagefile.files[0]
Any idea?
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
Related
I would need to find a solution to send via a single axios POST request both of the following:
json structure
binary file (excel file)
How can I achieve this?
let files = event.target.files;
const fileReader = new FileReader();
fileReader.readAsText(files[0], null);
fileReader.onload = () => {
this.fileContent = fileReader.result;
let binaryDataForObject = this.fileContent;
let referenceDataStructure = {
textData: textDataForObject,
binaryData: binaryDataForObject,
referenceDataFileExtension: this.referenceDataFileExtension,
userProvidedDataTypes: this.columnTypes
};
}
this.axios
.post(
"http://url,
referenceDataStructure
)
This works technically but on the java side I couldn't figure out, how to decode the binary data (encoded as a string) so that it is treated as an excel file.
Thank You in advance for any meaningful responses.
Lubos.
With simple POST request you can send only up to 1mb of binary data
To send binary and text in one request you should use FormData
Check out this answer for information
Update 14.12
How I managed to do this in my recent project was using FormData
So firstly you need to get file as a blob:
const fileReader = new FileReader()
// Here we will get the file as binary data
fileReader.onload = () => {
const MB = 1000000;
const Blob = new Blob([fileReader.result], {
// This will set the mimetype of the file
type: fileInputRef.current.files[0].type
});
const BlobName = fileInputRef.current.files[0].name;
if (Blob.size > MB) return new Error('File size is to big');
// Initializing form data and passing the file as a param
const formData = new FormData();
// file - field name, this will help you to read file on backend
// Blob - main data to send
// BlobName - name of the file, default it will be name of your input
formData.append('file', Blob, BlobName);
// Append json data
formData.apped('some-key', someValue)
// then just send it as a body with post request
fetch('/api/submit-some-form-with-file', {
method: 'POST',
body: formData
})
// Handle the rest
.then()
}
fileReader.readAsArrayBuffer(fileInputRef.current.files[0])
You can wrap this example in handle submit function in react and like or use it as is
I am using the following code to send a list of files to the backend:
var formdata = new FormData();
if(fileObjectList.length>0){
Object.keys(fileObjectList).forEach(i => {
formdata.append('file' + i, fileObjectList[i]);
});
}
formdata.append('requestModel', JSON.stringify(request));
req.open("POST", 'contorller');
req.send(formdata);
The controller converts the file to base64 data.
To send the data via email, we have to attach the content as base64,
which I again send to the controller as a file object.
You can use jszip to add files in a zip and send whole doc as base64 in single request. check the below link for more information jszip
var jszip = new ZipHandler;
var formdata = new FormData();
if(fileObjectList.length>0){
Object.keys(fileObjectList).forEach(i => {
jszip.addFile(`${fileObjectList[i]}.fileTypeExt`, '(buffer|base64)');
});
};
var zipcomplete = await t.generate({
base64: !0,
compression: "DEFLATE"
});
formdata.append('fileDataZip', zipcomplete);
formdata.append('requestModel', JSON.stringify(request));
req.open("POST", 'contorller');
req.send(formdata)
by using C# use below code to save base64 file
System.IO.File.WriteAllBytes("/fileDataZip.zip", Convert.FromBase64String(fileDataZip));
By using nodejs utilize the below code to save base64 file
require("fs").writeFile("fileDataZip.zip", fileDataZip, 'base64');
I need to send an image from client to server using blob
I have converted a image to BLOB in jquery (client side) and sending the blob to python flask (server side) the problem is, I can't recreate image from BLOB. I have tried the following code in python but failed to get the image
Jquery code to convert image to blob:
function changeFile() {
var file = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', readFile);
reader.readAsText(file);
}
function readFile(event) {
document.body.textContent = event.target.result;
console.log(event.target.result);
appendFileAndSubmit(event.target.result);
}
function appendFileAndSubmit(imageUrl){
var ImageURL = imageUrl
var data = {
'logo':ImageURL
}
$.ajax({
url: 'http://sdsdss/User/imgBlob',
method: 'POST',
dataType : 'json',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
}).done(function(response){
var datas = JSON.parse(response);
console.log(datas);
});
}
document.getElementById("inp").addEventListener("change", changeFile);
Python Code: To recreate BLOB to image
function getImage(self):
reqData = json.loads(request.data)
Logo = reqData['logo']
png_recovered = base64.decodestring(Logo)
f = open("temp.png", "w")
f.write(png_recovered)
f.close()
Don't read the file as text, You are dealing with binary data. Best way to transfer binary with json is if you read the file as base64 instead reader.readAsDataURL(file) This will encode all bytes to a web safe base64 string (no slash or plus). Then you have to decode it with python as well.
I discourage you from using json when dealing with file transfer as it will increase the bandwidth with ~3 times as much (not to mention the time it also takes to decode and encode it back and forth) For this I recommend you instead use FormData.
var fd = new FormData()
fd.append('logo', files[0])
$.ajax({
url: 'http://sdsdss/User/imgBlob',
method: 'POST',
data: fd,
// Setting false prevent jQuery from transforming the data
processData: false,
contentType: false
}).then(function(response) {
console.log(JSON.parse(response))
})
or simpler yet, just post the file without any formdata, json or extra fields if they are not necessary.
fetch(uploudUrl, { method 'PUT', body: this.files[0] })
I'm using keditor for my document. My problem here is that the images are generated as blob and I have no way of knowing where they are being stored thus when converting the file to another format the images are lost.
Sample image tag with blob:
<img src="blob:http://localhost/7b0e82ab-445b-4866-b8b5-09b4881a0544" width="100%" height="" style="display: inline-block;">
I was hoping I can find a way to convert this to blob either using PHP or JS.
I also found this post but no solution was provided:
JS convert blob url to Base64 file
Somewhere in your code you have a reference to the blob that you had to get your blob url, take it an pass it to the FileReader like so:
// Just an example file
var blob = new Blob(['abc'], {type: 'text/plain'})
var reader = new FileReader()
reader.onload = function() {
var base64data = reader.result
console.log(base64data)
}
reader.readAsDataURL(blob)
Using AJAX:
$.ajax({
method: "GET",
url: "blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc",
dataType: "binary",
}).done(function( data ) {
var reader = new FileReader();
reader.readAsDataURL(data);
reader.onloadend = function() {
var base64data = reader.result;
console.log(base64data)
}
});
Have not tested this, but should point you in the right direction though.
I need upload image with AngularJS without form. but I don't know how to receive it in Laravel, send it.
My code is this:
<input type="file" name="file" accept="image/jpeg, image/png" id="file" ng-model="data.image">
$('input[type=file]').change(function () {
$scope.img = this.files[0];
var filePath = $("#file").val();
var reader = new FileReader();
reader.onload = function (e) {
$('#image').attr('src',e.target.result);
$scope.img["imgbase64"] = e.target.result;
};
reader.readAsDataURL(this.files[0]);
});
I use the service here:
var imgSend = new FormData();
imgSend.append("file",$scope.img);
data["image"] = imgSend;
url = "maquinas"; registroMaquinaServices.servicesRegistroMaquinaPost(url,data).then(function(promise){
var requests = promise.data.response;
console.log(requests);
})
I'm sending this to laravel.
Thanks.
You can use https://github.com/ghostbar/angular-file-model
to handle your image file for uploading and then you will be able to create form object and send it to your laravel server to be able to get the image file as regular uploaded file, not a base64 encoded one.
this is the code i use to do so
in the example all of the data that needs to be sent to server is in $scope.data variable
$http({
headers: {
'Content-Type': undefined //undefined value is on purpose
},
method: method,
url: url,
data: $scope.data,
transformRequest: function(data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function(value, key) {
formData.append(key, value);
});
return formData;
}
})