Download link excel in vuejs - laravel

In controller laravel: I use box/spout , I save the excel file in a separate folder, and i create a variable that points to the folder where the file is saved, and i return the vuejs view to download that file
$path = '/files/'.$name;
$urlFile = url('/files/'.$name);
var_dump($urlFile);
// Result:
http://localhost.loca/file/data.xlsx
I return view vuejs:
return response()->json($urlFile);
View vuejs :
methods: {
// event button click
clickButton() {
axios
.get("/api/export")
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
// I want to download this link !
})
.catch((error) => {
console.log(error);
});
}
}
Please give me idea download link ? Thanks
Update: I use window.open(res.data) but it doesn't work

Try to create an anchor and click on it programmatically to download the file :
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
//create and append anchor download to body
const downloadAnchor = document.createElement("a");
downloadAnchor.setAttribute("href", "http://localhost.loca/file/data.xlsx");
downloadAnchor.setAttribute("download", "data.xlsx");
document.body.appendChild(downloadAnchor);
downloadAnchor.click();
//remove anchor download
document.body.removeChild(downloadAnchor);
})

If window.open doesn't work you can try this:
function download(url) {
const a = document.createElement('a')
a.href = url
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
And then call the download function in your method:
methods: {
// event button click
clickButton() {
axios
.get("/api/export")
.then((res) => {
console.log(res.data) // http://localhost.loca/file/data.xlsx
download(res.data)
})
.catch((error) => {
console.log(error);
});
}
}

Related

Form data sends empty request to the server

I am using vuejs and laravel to make a panel for admin
I understand i can not send any files without form data
so i gotta use formData like this
onSubmit(evt) {
evt.preventDefault();
this.emptyValidator();
let data = new FormData();
console.debug(this.form)
for (let input in this.form) {
data.append(input, this.form[input]);
}
data.append('image', this.image);
console.debug(data)
console.debug(this.image)
ProductDataService.update(this.id, data)
.then(response => {
let data = response.data;
if (data.data) {
Swal.fire('edited successfully', '', 'success');
}
})
.catch(error => {
if (error.response.status && error.response.status === 422)
this.handleValidation(error);
})
},
Note: i am using it in production mode
and when i try to dd in laravel it shows me empty
i did not have any problem with sending manual and formData in edit is a pain in my ass

how to upload image in register API in strapi?

In defaut registration API, I need to uplaod the image of user in registration API. So how could I manage it ? I'm sending in a formData and it works fine. I can see (binary) in network.
I tried to add image field and it works in admin panel but from API side I tried to send the file in key names like files, profileImage.
I didn't get the error in res. I got success in res.
Issue: When I reload the admin panel, I didn't get user's profile image.
Try this way. I used in react and it works fine for me.
signUpHandler = () => {
console.log("SignUp data ::: ", this.state);
let data = {
username: this.state.signUpForm.username.value,
phone: this.state.signUpForm.phone.value,
email: this.state.signUpForm.email.value,
password: this.state.signUpForm.password.value
}
axios.post('http://0.0.0.0:1337/auth/local/register', data)
.then(res => {
console.log(res);
return res.data.user.id;
})
.then(refId =>{
const data = new FormData();
data.append('files', this.state.selectedFile);
data.append('refId', refId);
data.append('ref', 'user');
data.append('source', 'users-permissions');
data.append('field', 'profileImage');
return axios.post('http://0.0.0.0:1337/upload', data)
})
.then(res =>{
console.log(res);
alert("You registered successfully...");
this.props.history.push('/login');
})
.catch(error =>{
console.log(error);
})
}
First, you will have to customize your user-permission
To do so, you will have to understand this concept: https://strapi.io/documentation/3.0.0-beta.x/concepts/customization.html
Then you will have to find the function you want to update - in your case, the register function.
And tada here it is https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L383.
So you will have to create ./extensions/users-permissions/controllers/Auth.js with the same content as the original file.
Then you will have to add
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
const uploadFiles = require('strapi/lib/core-api/utils/upload-files');
on the top of your file.
And in your function use this
const { data, files } = parseMultipartData(ctx); to parse data and files.
Then you will have to replace ctx.request.body by data to make sure to use the correct data.
After that you will have to add this after the user creation line
https://github.com/strapi/strapi/blob/master/packages/strapi-plugin-users-permissions/controllers/Auth.js#L510
if (files) {
// automatically uploads the files based on the entry and the model
await uploadFiles(user, files, { model: strapi.plugins['users-permissions'].models.user })
}
Solution for Strapi v4:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer XXXX");
var formdata = new FormData();
formdata.append("files", fileInput.files[0], "XXX.png");
formdata.append("refId", "46");
formdata.append("field", "image");
formdata.append("ref", "plugin::users-permissions.user");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("http://localhost:1337/api/upload", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

How I can upload a file using html input type "file" through ajax with web API model binder

I'm using a MVC 5 web Api Controller, and I want my data coming through ajax with file to automatically bind?
You can append your uploaded file to FormData and send it via Fetch API.
Here's a demo to get started:
window.onload = () => {
document.querySelector('#myFile').addEventListener('change', (event) => {
// Just upload a single file, if you want multiple files then remove the [0]
if (!event.target.files[0]) {
alert('Please upload a file');
return;
}
const formData = new FormData();
formData.append('myFile', event.target.files[0]);
// Your REST API URL here
const url = "";
fetch(url, {
method: 'post',
body: formData
})
.then(resp => resp.json())
.then(data => alert('File uploaded successfully!'))
.catch(err => {
alert('Error while uploading file!');
});
});
};
<input id="myFile" type="file" />
After that just get the file from the current request in your API action method.
[HttpPost]
public IHttpActionResult UploadFile()
{
if (HttpContext.Current.Request.Files.Count > 0)
{
var file = HttpContext.Current.Request.Files[0];
if (file != null)
{
// Do something with file now
}
}
return Ok(new { message = "File uploaded successfully!" });
}

Add custom headers to upload image

I'm currently trying to integrate the CKeditor 5 ReactComponent into my app.
I'm facing an issue with the upload image functionality... I use a Node/Express backend which uses a JWT auth middleware, so each request must have an Authorization header in order to pass.
I want to know if one of the following is possible:
a way to add a custom header to the component
a way to overwrite the upload handler and call a custom handler instead in which I can do what ever
Below is my code
<CKEditor
editor={ClassicEditor}
data="<p>Add product description here</p>"
onInit={(editor) => {
// You can store the "editor" and use when it is needed.
//console.log('Editor is ready to use!', editor);
}}
onChange={(event, editor) => {
const data = editor.getData();
this.handleData(data)
}}
config={{
ckfinder: {
uploadUrl: `${apiUrl}/upload/images/description`,
},
}}
/>
Thanks
try it with this code in property onInit
onInit={ editor => {
editor.plugins.get( 'FileRepository' ).createUploadAdapter = function( loader ) {
return new UploadAdapter( loader );
};
}}
after you must create the class UploadAdapter
class UploadAdapter {
constructor( loader ) {
// Save Loader instance to update upload progress.
this.loader = loader;
}
upload() {
const data = new FormData();
data.append('typeOption', 'upload_image');
data.append('file', this.loader.file);
return new Promise((resolve, reject) => {
axios({
url: `${API}forums`,
method: 'post',
data,
headers: {
'Authorization': tokenCopyPaste()
},
withCredentials: true
}).then(res => {
console.log(res)
var resData = res.data;
resData.default = resData.url;
resolve(resData);
}).catch(error => {
console.log(error)
reject(error)
});
});
}
abort() {
// Reject promise returned from upload() method.
}
}

axios get request link error in url of a click event

I am trying to get the id of a click event in axios vue.js in laravel, but I am getting the url wrong in console.
http://{mylink}/messages/getMessages1
instead of
http://{mylink}/messages/getMessages/1
I want the output as the second url.
My method in file.js looks like this:
methods:{
messages:function(id){
let vm = this;
this.$http
.get('messages/getMessages' + id)
.then(response => {
console.log(response.data);
vm.privateMsgs = response.data;
})
.catch(function (error) {
console.log(error.response);
});
}
the route looks like this:
Route::get('/messages/getMessages/{id}','Messages#getuser');
and the controller looks like this:
public function getuser($id){
echo $id;
}
please guide me to make this correct.
You are missing the slash in your axios request. It should be:
.get('/messages/getMessages/' + id)
I checked and the code is working properly.
messages:function(id){
var self = this;
this.$http.get('/messages/getMessages/' + id)
.then(response => {
console.log(response.data);
this.privateMsgs = response.data;
})
.catch(function (error) {
console.log(error.response);
});
}

Resources