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;
}
})
Related
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'
}
})
I have a node.js server, which uses express-fileupload to accept images. Now I'm working on the function to upload an image. But I don't want to use < form > since I prefer xhtml request for various reasons, but mainly because I don't want to redirect the user, after he uploads an image.
I have tried reading the picture as dataURI, sending it to the server, decoding it and writing it to a file, which didnt work and seemed to resource intensive and laborious.
//I used the dataString from the callback method and wrote it to a file using fs.writeFile
function dataURItoimage(dataString, callback){
const atob = require("atob");
dataString.replace("data:image/jpeg;base64,", "");
dataString.replace("data:image/png;base64,", "");
atob(dataString);
callback(null, dataString);
}
//User side code
avatarInput.addEventListener("change", (e) => {
const reader = new FileReader();
reader.readAsDataURL(avatarInput.files[0]);
reader.onload = () => {
avatar = reader.result;
tosend.avatar = reader.result;
}
}, false);
uploadButton.onclick = () => {
var request = new XMLHttpRequest();
request.open("POST", "/avatarUpload");
request.setRequestHeader("Content-Type", "application/json");
var tosend = {avatar: ""};
tosend.avatar = avatar;
request.send(JSON.stringify(tosend));
}
Is there a better way to upload an image, which the user can select, to a node.js server?
You can try this example. It worked for me. I hope it can help you.
Sending dataURL throw Ajax request:
const dataURL = snapshotCanvas.toDataURL('image/png');
$.ajax({
url: 'http://localhost:3000/upload-image',
dataType: 'json',
data: { data: dataURL },
type: 'POST',
success: function(data) {}
});
Receiving request:
router.post('/', (req, res) => {
const base64 = req.body.data.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(`uploads/images/newImage.jpg`, base64, {encoding: 'base64'});
}
So I did it this way:
var request = new XMLHttpRequest();
request.open("POST", "/test");
var fd = new FormData();
fd.append("file", avatarInput.files[0]);
request.send(fd);
I created a FormData Object, appended the image, which the user chose in an input called "avatarInput", and send the object to the server.
On server side I used express-fileupload to access the file:
app.post("/test", (req, res) => {
if(req.files){
//With the follwing command you can save the recieved image
req.files.file.mv("./file.png", (err) => {if(err)throw err});
}
res.end();
});
I want to read a file from local storage and upload it via ajax. How is this done?
In most browsers, you can use FileReader to read data from file inputs. There are various functions for reading the data; this example uses the function that returns an ArrayBuffer containing all the bytes:
<script>
window.onload = function() {
document.getElementById('upload').onchange = function(e) {
var file = e.target.files[0];
var fileReader = new FileReader();
fileReader.onload = function(e) {
var bytes = e.target.result;
console.log(bytes);
};
fileReader.readAsArrayBuffer(file);
};
};
</script>
<input type = 'file' id = 'upload' />
I managed to figure it out. Here's the code for anyone interested.
var form = new FormData();
form.append("data", angular.toJson(message));
var bytes = new Uint8Array(audio.length); //audio is an IBuffer
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(audio);
dataReader.readBytes(bytes);
dataReader.close();
var media = new Blob([bytes], { type: "application/octet-stream" }); //application/octet-stream or audio/mpeg?
form.append("attached_files", media, "recording-aac.caf");
return $http.post(AppSettings.baseUri + "api/sendmessage", form, { headers: { "Content-Type": undefined } });
I've some trouble into uploading a video to a form.
In my case, I need to upload some data with my video, so I left BackgroundUploader to use WinJS.xhr. But I can't figure it out how to convert my video file into something readable for my php.
My code:
var clickPicker = function () {
openPicker = Windows.Storage.Pickers.FileOpenPicker();
// We set the default location to the video library
openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.videosLibrary;
// Set de view to thumbnail
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
// Extension allowed to be taken
openPicker.fileTypeFilter.replaceAll([".mp4", ".avi"]);
openPicker.pickSingleFileAsync().done(function (file) {
uploadInit(file);
}, function (err) {
// MISTAAAAAAAAAAAAAAAAKEEEEEEEEE
console.log(err.message);
});
};
var uploadInit = function (file) {
// Creating the blob
var objectURL = window.URL.createObjectURL(file);
var url = "http://localhost/vdm_bo/videos/uploader";
var d = new Date();
var data = new FormData();
data.append("data[Video][pseudo]", 'H4mm3R');
data.append('data[Video][postal_code]', '67340');
// Converting date to a datetile mysql
data.append('data[Video][date]', ISODateString(d));
data.append('data[Video][age]', '24');
data.append("data[Video][email]", 'bliblu#hotmail.fr');
data.append("data[Video][question_selected]", 'qA');
data.append("data[Video][video_file]", file, file.name);
WinJS.xhr({
type: "POST",
url: url,
data: data
}).done(function (res) {
console.log('succes');
}, function (err) {
console.log(err.message);
}, function (res) {
});
};
So, to debug this I serialize the answer, and here is what I get :
When uploading with the file (without blob) :
s:36:"[object Windows.Storage.StorageFile]";
When uploading with blob (window.URL.createObjectURL(file))
s:41:"blob:9A06AB11-8609-42DC-B0A9-7FB416E70A9D";
And when I'm uploading the video just with my html form
a:5:{s:4:"name";s:36:"9147cb17e216d5182908ad370ff16914.mp4";s:4:"type";s:9:"video/mp4";s:8:"tmp_name";s:23:"C:\wamp\tmp\php13C8.tmp";s:5:"error";i:0;s:4:"size";i:26454182;}
Does anyone have a clue how to make it work ? Or maybe I do it all wrong and it's not the way I'm suppose to convert my file (It's the way to do for images, maybe not for video)
Okay, I found a way to do that. First ou need to get the file with getFileAsync() and not the Picker. Then you can create a blob with the stream of your file and add this blob to your form.
Here my code
var videosLibrary = Windows.Storage.KnownFolders.videosLibrary;
videosLibrary.getFileAsync(file.name).then(
function completeFile(file) {
return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
}).then(
function completeStream(stream) {
var d = new Date();
// Do processing.
var blob = MSApp.createBlobFromRandomAccessStream("video/mp4", stream);
var data = new FormData();
data.append("data[Video][pseudo]", 'H4mm3R');
data.append('data[Video][postal_code]', '67340');
// Converting date to a datetile mysql
data.append('data[Video][date]', ISODateString(d));
data.append('data[Video][age]', '24');
data.append("data[Video][email]", 'bliblu#hotmail.fr');
data.append("data[Video][question_selected]", 'qA');
data.append("data[Video][video_file]", blob, file.name);
return WinJS.xhr({ type: "POST", url: "http://localhost/vdm_bo/videos/uploader", data: data });
}).then(
function (request) {
console.log("uploaded file");
},
function (error) {
console.log("error uploading file");
});
I am receiving an error trying to upload large than 50kB file via jQuery Ajax POST request.
I am sending the request to OData service ( ASP.Net MVC application)
The error I am receiving in browser console is " 413 Request Entity Too Large "
Below is the code I am using to upload
var fileData =
{
fileBinaryData: encodedData //file data in encoded format ( 64 bit),
Description: "my first file"
};
fileData = JSON.stringify(fileData);
$.ajax({
url: // some odata url ,
type: "POST",
data: fileData,
success: function (res) {
// do something
},
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Accept", "application/json");
}
});
a) Is code above the correct way to upload file data via jQuery ajax to a service
b) I have modified my web.config to accept large requests.
c) I do not want to use plugin's like uploadify etc
EDIT 1:
I used javascripts' FileReader() to read the file.
var reader = new FileReader();
//then applied reader.onloadend method etc
if (file.webkitSlice) {
var blob = file.slice(start, stop + 1);
} else if (file.mozSlice) {
var blob = file.mozSlice(start, stop + 1);
}
reader.readAsBinaryString(blob);
Finally settled with using jQuery fileUpload plugin