Post file using javascript to Laravel Controller using request object - javascript

I am new to laravel and i want to send a file to a controller using javascript. I've seen examples for FormData object but i do not want to use that because i want to get file object from Request Object in controller. Instead of FormData i am making a request_data string. i am successfully able to post string variables but when i put file inside that request_data string i am not unable to get the file inside controller. Below is my code.
javascript
var file = form.task_file.files[0];
var http = null;
var url = "http://".concat(window.location.hostname).concat("/pms/upload_task_file");
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
}
http.onreadystatechange = function () {
alert(http.response);
}
const request_data= `task_file=${file}`;
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'multipart/form-data');
http.setRequestHeader("X-CSRF-Token", form.token.value);
http.send(request_data);
Controller
public function uploadFile(Request $req)
{
if ($req->hasFile('task_file')) {
echo 'Request Contains a file';
} else {
echo 'No File in Request Object';
}
}
In response i always get 'No File in Request Object'. What is the correct way of posting file to controller using java script using request_data. Please help.

Try using the FormData in ajax while you upload a file.
$('form').submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '{{ url('/agents') }}',
type: 'POST',
data: formData,
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});

var http = new XMLHttpRequest();
http.onreadystatechange = function(response){
if(http.status === 200 && http.readyState){
console.log(response)
}
}
http.setRequestHeader('Content-type', 'multipart/form-data');
http.setRequestHeader("X-CSRF-Token", form.token.value);
http.open('get','https://jsonplaceholder.typicode.com/todos/1')
http.send()

Related

How can a Json return be sent from a controller to the frontend in Asp.NET Core MVC application?

So, I have a JS script that sends a request to the server and that works fine. However, I want the frontend to recieve a response containing some information and read it on the frontend and execute a function.
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
if (request.response.result == "Success") {
console.log("Result is success")
window.location = request.response.url;
}
}
My controller looks like this.
[HttpPost("/page/upload")]
public IActionResult Upload()
{
*working parts pertaining to reading the request are omitted*
var redirectUrl = Request.Host + "/" + page.PageURL;
return Json(new { result = "Success", url = redirectUrl});
}
What I want is for my JS script to access the returned Json and its contents. How would I do this?
Try using the following code. It will subscribe the readystatechange event and run when API response has been received
uploadButton.addEventListener("click", () => {
var formData = new FormData();
var request = new XMLHttpRequest();
request.open("POST", "/Page/Upload");
request.send(formData);
request.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
var responseData = JSON.parse(this.responseText);
if (responseData.result == "Success") {
console.log("Result is success")
window.location = responseData.url;
}
}
});
});

Upload images to a Node.JS server without using <form>

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();
});

How to download and then upload image with AngularJS

I have an Angularjs 1.5.0 web application which should communicate with a REST-based web service that I had developed (using dropwizard & jersey) and tested that it works perfectly.
The REST web service method is like this:
#POST
#Path("/saveImage")
public Response saveImage(
#FormDataParam("imagefile") InputStream uploadedInputStream,
#FormDataParam("imagefile") FormDataContentDisposition fileDetail) {
// save image on server's file system and return OK
}
Scanned images are available to me by the scanner's local web server through a link like this: http://localhost:9980/thumb/random-generated-guid.jpg
In my angularjs code, I want to send the image which is available with the link above to my REST service.
Does anybody know how to do this?
I tried first saving the image as a blob and then send it to the web service. I could save the image using javascript's XMLHttpRequest but sending always fails.
Code for saving the image as Blob:
var xhr = new XMLHttpRequest();
xhr.open('GET', imageAddress, true);
xhr.responseType = 'blob';
var imageData = null;
xhr.onload = function(e) {
if (this.readyState === 4 && this.status === 200) {
// get binary data as a response
imageData = this.response;
var gatewayResponse = sendToGateway(imageData);
}
};
Code for sending the blob data:
var sendToGateway = function(imageDataBlob) {
var formdata = new FormData();
formdata.append('imagefile', imageDataBlob)
$.ajax({
url: 'http://localhost/eval/saveImage',
method: 'POST',
contentType: 'multipart/form-data; charset=UTF-8',
data: formdata,
dataType: 'json',
})
.done(function(response) {
$log.info("**************** response = " + response);
alert("response:\n" + response);
})
.fail(function(jqXHR, textStatus, errorThrown) {
$log.error("!!!! FAIL !!!!!!!!!");
alert("FAIL !!!!!!!");
})
.always(function(){
$rootScope.scannerInactive = false;
doStartPreviewUpdate();
});
};
Actually, the problem is when the sendToGateway(imageData); is called, I get the error:
TypeError: 'append' called on an object that does not implement
interface FormData.
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" :
value );
oops, I found the problem. I should have added the following directives to the $.ajax() call.
processData: false,
contentType: false,

TideSDK Call PHP file w/ Ajax

So, TideSDK say that php is preprocessed upon each request (if it's a .php file).
I'm using the following JS ajax:
function ajax(url, method, data, async)
{
method = typeof method !== 'undefined' ? method : 'GET';
async = typeof async !== 'undefined' ? async : false;
if (window.XMLHttpRequest)
{
var xhReq = new XMLHttpRequest();
}
else
{
var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
}
if (method == 'POST')
{
xhReq.open(method, url, async);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(data);
}
else
{
if(typeof data !== 'undefined' && data !== null)
{
url = url+'?'+data;
}
xhReq.open(method, url, async);
xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhReq.send(null);
}
return xhReq.responseText;
console.log("[ajax] Request Completed.");
}
and my index.php file is:
<?php echo "Test"; ?>
ajax is called as such
console.log(ajax('index.php', 'GET'));
Instead of returning 'Test' it just returns the source code.
Am I doing something wrong, or is this expected. Other-wise, what could I do too get the expected output: the pre processed PHP.
If you want to do a ajax get request on your php script, use the jQuery ajax method.
RTM: http://api.jquery.com/jquery.ajax/
Example GET Request:
$(document).ready(function()
{
$.get("index.php", function(data) {
console.log(data);
});
});
Example POST Request:
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "index.php",
data: { "test": "hello world", "anotherkey": "andvalue" },
success: function(data) {
console.log(data);
}
});
});
// usage in php: $post_test = $_POST['test']; // returns 'hello world'

Error 'Illegal Invocation' while trying to convert javascript to jquery

I am trying to convert some code from javascript to jquery.
Javascript Code: (I have got this code here)
window.onload = function () {
document.getElementById('uploader').onsubmit = function () {
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('fileInput');
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
}
}
JQuery Code: (According to my application)
$('#AutoUploadFiles').click(function () {
var formdata = new FormData();
var fileInput = $("#AutomaticUploader");
for (var i = 0; i < fileInput.get(0).files.length; i++) {
formdata.append(fileInput.get(0).files[i].name, fileInput.get(0).files[i]);
}
$.ajax({
url: '/members/AutoUploadFile',
type: 'post',
data: formdata,
success: function () {
},
error: function () {
}
});
});
When I try to execute the above JQuery code I get 'Illegal Invocation' error in jquery.min.js file.
I am new to Web Programming, so I might have done some mistakes while converting to JQuery.
If anybody catches some mistake, please guide me.
the problem is the formdata is an object and can't be serialize as an ordinary string
var formdata = new FormData();
and in your code
type: 'post',
data: formdata, //<-- this is the problem
success: function () {
formdata must be serialize well as valid json data or else it can't be send by $.ajax() that's why your jquery version will not work. Please try other jquery uploader scripts because there are lot of them in google
The accepted answer doesn't work if you are sending files over the XHR as file objects can not be JSON encoded.
The only "workaround" is to disable jQuery's XHR data processing.
To disable it globally use
$.ajaxSetup({processData:false});
or do
$.ajax({
... Ajax Stuff Here,
processData: false
});
on each request.

Categories