Cannot download file Symfony 3.4 and VueJS - php

I spent time before asking this question
I want to download file from local directory /Users/Desktop/symfony/project_dem/app/Resources/file.webm, but i always get something wrong.
So my controller
public function getUrl(Request $request)
{
$response = new BinaryFileResponse($file);
$response->setAutoEtag(true);
$response->headers->set('Content-Type', 'video/webm');
return $response;
}
in VueJS
axios.post('/api', {
url: this.url,
responseType: 'blob',
}).then((response) => {
console.log(response.data);
let blob = new Blob([response.data], {
type: 'video/webm'
}),
url = window.URL.createObjectURL(blob);
window.open(url);
}).catch(error => {
console.log(error);
});
I get in console log for response.data like this
**
What I found wrong is why the size of the file in server 6.2 MB and after a download is 11.2 maybe this is error BinaryFileResponse ?
**
Anyone can tell me what I did wrong ? and thanks.

So it seems that the output of console.log(response.data) is showing a binary file. I mean the file is there. You are not clear when you say
but I always get something wrong
Try this
axios.post('/api', {
url: this.url,
responseType: 'blob',
}).then((response) => {
let blob = new Blob([response.data], {
type: 'video/webm'
});
url = window.URL.createObjectURL(blob);
window.open(url);
}).catch(error => {
console.log(error);
});
In my opinion, the issue here is that you did not put a semi colon at the end of the line where you created the blob.

Related

Vue axios 404 err

I have a problem when making an axios request, it returns a 404 error, the file path is fine since it is in the same directory and I do not understand why it returns that error,
I am using vue-cli, and I run the server with npm run serve instead of express.
Register.vue
var formData = new FormData();
formData.append("nombre", nombre);
formData.append("mail", mail);
formData.append("pass", pass);
axios
.post("./auth_register.php", formData)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
auth_register.php
<?php
if (isset($_POST['nombre']) && $_POST['mail'] && $_POST['pass']) {
return json_encode("received");
} else {
return null;
}
I don't know why this happens
I am new to vue do not be angry
Try using the full path; Worked for me! after long searching
example -> http://localhost:8080/api/authentication/login.php

slim 4 - multiple file upload empty $_FILES array

I'm havong some trouble to upload multiple file at once in my vue and php app. I'm using slim to have an endpoint where upload request is posted:
On the server side I have this code to test if all works fine:
$app->post('/compress', function(Request $request, Response $response){
$files = $request->getUploadedFiles();
var_dump($files); // this will result in empty
//return $response;
});
In my javascript code, inside a vue method I have this code that is called when the file input will change:
let formData = new FormData();
for(let i; i < this.$refs.selectedImages.files.length; i++){
formData.append('images[]', this.$refs.selectedImages.files[i]);
}
let config = {
header: {
'Content-Type': 'multipart/form-data',
},
withCredentials: true
}
axios.post('http://localhost:3000/compress', formData, config)
.then( (response) => {
console.log(response, response.data);
});
tha result is that the var_dump will give me empty. How I can fix?
Can you try this one?
for( var i = 0; i < this.$refs.selectedImages.files.length; i++ ){
let file = this.$refs.selectedImages.files[i];
formData.append('images[' + i + ']', file);
}
After a lot of debug I've fixed the code. The problem was with the for() loop that seems not working to iterate FileList in my case. I've replaced it with a forEach() and voilĂ ! The server started to get the uploaded files.
let files = this.$resf.selectedImages.files;
let formData = new FormData();
files.forEach( (el) => {
formData.append('images[]', el);
});

Image upload issue with react-native and PHP(CodeIgniter) as backend

I have an app scenario with react native and CodeIgniter as backend.
I have a code snippet to upload image as picked by react-native-image-picker as below:
let formData = new FormData();
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
formData.append('file', (imageBody)) // case 1 gives network error
formData.append('file', JSON.stringify(imageBody)) //case 2 goes OK
apiUpdateUser(formData)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
The apiUpdateUser method goes as :
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
The Php code at the backend to handle this upload as usual is:
$file=$this->request->getFile('file');//in CI
$file=$_FILES['file'];//in normal php
My issue is that I do not get anything whatsoever in the $file variabe with either of the methods, The file variable is empty in both the cases.
I've checked the implementation in react native and it doesnt seem to be buggy at all comparing with tutorials/demonstrations online. Also the way of handling at the backend is obvious and Ok.
I'm able to achieve this upload with POSTMAN easily but with react-native I'm facing this error. Can anyone show me some light here??
I am using VUE and sending files using Axios. So I think this may help you out.
I am using the following way of form data to set the files or images.
formData.append('file', this.form.image_url, this.form.image_url.name);
Here this.form.image_url directly refers to the $event.target.files[0]; where $event targets the input.
In the backend, it is the same as you have it here.
This works out well for me. I am unsure of what you are passing as imageBody so it's hard to comment on that.
You can try this
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
apiUpdateUser(imageBody)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
Turns out that the JSON.stringify() was the culprit line.
Without that line, the app was giving out network error.
That's why I had randomly added it just to see if that was the cause of error.
Since, the network error issue was solved with that addition, I didn't give a second thought about it and only thought it to be a file upload issue. Actually, I now see that this is a known issue of a react native flipper version that I have been using which I managed to solve.

React Native uploading Image to php page on server

I have PHP page on a web server to upload image from React Native.
Using Postman method POST, form-data key:avatar value: image_file everything works as expected.
In React Native I tried:
let uploadData = new FormData();
uploadData.append('avatar', uploadUri);
fetch(base_url, { method: 'post,', body: uploadData }).then(
(res) => {
var myresponse = res;
console.log(JSON.stringify(myresponse));
//console.log(res);
}
);
I am getting from server error:
{"type":"default","status":400,"ok":false,"headers":{"map":{"server":"Apache","connection":"Upgrade,
close","content-type":"text/html","vary":"Accept-Encoding,User-Agent","date":"Wed,
20 May 2020 15:29:15
GMT","accept-ranges":"bytes","upgrade":"h2,h2c"}},"url":"http://www./uploadImage.php","_bodyInit":{"_data":{"size":10154,"offset":0,"blobId":"D8041FEE-0479-4CD5-8438-4EFD737561DE","type":"text/html","name":"uploadImage.php","__collector":{}}},"_bodyBlob":{"_data":{"size":10154,"offset":0,"blobId":"D8041FEE-0479-4CD5-8438-4EFD737561DE","type":"text/html","name":"uploadImage.php","__collector":{}}}}
Than I tried using axios:
let uploadData = new FormData();
uploadData.append('avatar', uploadUri);
axios.post(base_url, uploadData).then((res) => {
console.log(res);
});
I get this response from the server:
"error": true,
"message": "No file was sent!",
"status": "error",
It is failing on: if($_FILES['avatar']), in PHP.
I have no idea what to do any more, again in Postman everything works fine as expected.
Does anybody have any idea what to do?
I tested it again and it is to be a problem with the URI that I am sending, for sure.
ie. if I look in Postman the request that I am sending:
avatar=#/Users/......image.jpg
and in React Native I am sending:
"avatar","file:///Users/.....image.jpg
By the way, I am using expo-image-picker to select the image.
It looks like this did the work..
let body = new FormData();
//Appending file to body
body.append('avatar', {
uri: uploadUri,
type: 'image/jpeg', //This is the file type .. you can define according to your requirement
name: 'avatar.jpg', //File name you want to pass
});
//Service call
fetch(base_url, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: body,
})
.then((res) => res.json())
.then((responseJson) => {
//GET RESPONSE SUCCESS OF FAILURE
console.log(JSON.stringify(responseJson));
})
.catch((error) => {
//ERROR
console.log(JSON.stringify(error));
});

View pdf stream in browser

I have a PDF file that I want to view in browser tab. I know that I can use file link directly to display it, but I want to read contents of file in a variable and use the variable to display file. Reason behind is, I want to delete the file immediately after reading in variable.
PHP:
$fdata = file_get_contents($tmppdf);
header("Content-type: application/pdf");
header("Content-disposition: inline; filename=".$tmppdf);
return $fdata;
Ajax:
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
// window.location.href = "/purchases/print" + '/' + purchase_id;
window.open('/purchases/print' + '/' + purchase_id, '_blank');
});
I am getting binary contents in result. Can someone help, what is wrong with my code.
UPDATE :
Changed my ajax code to below and now I am getting a blank pdf page
$('body').on('click', '.printInvoice', function () {
var purchase_id = $(this).data("id");
$.ajax({
type: "GET",
url: "/purchases/print" + '/' + purchase_id,
success: function (data) {
var blob = new Blob([data], {type: 'application/pdf'});
var blobURL = window.URL.createObjectURL(blob);
window.open(blobURL,'_blank');
},
error: function (data) {
alert("Unable to Print !!!");
}
});
Perhaps:
return Response::make($fdata, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$tmppdf.'"'
]);
Laravel actually has built-in functionality to return file responses. This will automatically set the correct headers so the file gets displayed in the browser.
return response()->file($tmppdf);
If you want to stream the file you can use this to display the file:
This worked with a binary string.
return Response::make($file, 200, [
'Content-Type' => 'application/pdf',
]);

Categories