I am trying to send a POST request to upload a file to my IPFS server. However I am unsure how can I upload a file into the body of the request. I have tried looking at the examples from Fetch API, but their example shows files uploaded from a form. While in my case, the files are already within my directory.
Update:
I have revised my code for sending a POST request to my IPFS server based on the documentation on Fetch API and I am now able to successfully send a request. However I am still stuck on how can I get the "fileInput" variable to reference a file from my directory. The current example only works if I have a html form.
I have tried nodejs fs library but I ran into issues where some of the functions are not available. It appears that using fs may pose certain security concerns from what I read. Would appreciate if I can have some advice on this.
var formdata = new FormData();
const fileInput = document.querySelector('input[type="file"]');
formdata.append(
"file",
fileInput.files[0],
`../../ipfs_files/${item._id}.png`
);
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch("http://localhost:5001/api/v0/add", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
you can also send data as base64 string and store it into the database then while accessing convert back to the original format.
Related
I'm working on a project where I need to upload many PDF files to a PocketBase collection.
I have all the files on my computer and I'd like to upload them using nodejs and the PocketBase JavaScript SDK. PocketBase expects me to send the file as a [file object], which is not possible in nodejs.
Ideally the code would look something like that:
const fileObject = loadFile(pathToFile);
const entry = {
nameField: "some-field",
fileField: fileObject
}
await pb.collection("my-collection").create(entry)
I didn't find any bits of code that could help creating a loadFile function.
You are supposed to send your form as multipart/form-data when uploading files to pocketbase.
Try:
const res = fetch(
"http://127.0.0.1:8090/api/collections/my-collection/records",
{
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: myFormWhichHasFiles,
}
)
Also, make sure you don't use JSON.stringify on your form when using multipart/form data.
Pro tip: if you leave out 'Content-type', it should default to multipart/form-data.
I am trying to accept the URL Encoded format in postman to post some data to the Vue JS app, I am using the below-encoded format, how can I achieve that which npm package should I use?
you can use axios
const axios = require('axios')
const params = new URLSearchParams()
params.append('name', 'Akexorcist')
params.append('age', '28')
params.append('position', 'Android Developer')
params.append('description', 'birthdate=25-12-1989&favourite=coding%20coding%20and%20coding&company=Nextzy%20Technologies&website=http://www.akexorcist.com/')
params.append('awesome', true)
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios.post(url, params, config)
.then((result) => {
// Do somthing
})
.catch((err) => {
// Do somthing
})
x-www-form-urlencoded data is sent via HTTP headers
Most HTTP headers are not visible to your front-end JavaScript application. They are only visible to the server responding to the request. You cannot read them directly from JavaScript running in a web browser.
However, there are options...
Change the source; have the POST request changed to a GET and encode the parameters in the URL
A reverse proxy for your application could convert from POST parameters to GET parameters with some additional coding or configuration
Receive the request on your server and feed them into your Vue.js application; use something like php/asp/etc to serve your html instead of static HTML files and embed the posted parameters in the generated HTML page
There may be other options if you are creative, but the simplest is the first - just change the source so it no longer posts data.
I resolved it by adding middleware(server-side code such as .net web API) and then redirected it using query string)
I'm using Axios in Vue.js to retrieve data from files. I have files on my server, and I just want to retrieve their content so I can display it.
It's working with almost any file type (txt, css, js...) I can retrieve their content with no problem. But when the file is a .html, I get a 404 error ("Error: Request failed with status code 404"). I'm sure the file is there; in fact, if I rename it to a .txt, axios has no trouble finding it.
Here's my code... Nothing out of the ordinary:
axios({
method: 'get',
url: '/src/library/test.html'
})
.then((result) => {
this.htmlContent = result.data;
})
.catch((error) => {
console.error(error);
});
It's my first time using Axios, so I'm having trouble seing what I'm missing. Any idea?
I have a Vue.js app which uses axios to interact with a Laravel API. I'm trying to make a POST request with an image file in it to upload in the backend.
The issue I'm having is that axios makes the POST request with empty payload.
I've tried sending it both as a plain JS object and with FormData. In both cases the request payload is empty. I've looked on the internet for hours but I was unable to find anything while trying to tackle the issue in the past few days...
This is how I make the request:
let fd = new FormData();
fd.append('file', this.file);
console.log(...fd) //shows the file is there with its data
axios
.post("/api/images", fd)
.then(response => {
//Handle success
})
.catch(errors => {
//Catch errors
});
This is how I get the file from the form:
let selectedImage = this.$refs.fileInput.files[0];
const reader = new FileReader();
reader.addEventListener('load', (event) => {
this.file = event.target.result;
});
reader.readAsDataURL(selectedImage);
I've tried experimenting with the request headers and at the moment they are as follows:
"Accept" : "application/json",
"Content-Type": "multipart/form-data; charset=utf-8; boundary=" + Math.random().toString().substr(2),
"Authorization": "Bearer " + this.user.api_token,
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content
The responses from Laravel are always that the file is required (as expected when it's indeed missing).
I did try encoding the file in Base64 but I have trouble validating that it's an image in the backend.
I found this similar question but it wasn't of any help: FormData sends empty data using axios
I want to send a file + JSON data but I'm ok with just making the file upload work. So... How do I send a file from Vue.js app to Laravel API using Axios? What am I doing wrong?
I am trying to upload file using React Dropzone on ftp with Reactjs + AXIOS at front end, Nodejs + connect-multiparty at back end.
The problem is when I am sending file via front end using AXIOS, I am not getting the file at server in request.
My code to upload file using react-axios is
let data = new FormData()
data.append('file', file)
var setting = {
method: 'post',
url: 'my-server-url',
data:data,
headers: {
'Content-Type': 'multipart/form-data'
},
}
var response = axios(setting).then(response => { return response.data })
.catch(response => response = {
success: 500,
message: "Your submission could not be completed. Please Try Again!",
data: ""
});
while using postman, everything works fine. Server side api is working. only problem with client side request code.
Any help!!!
This is a very rookie mistake you're making probably because of the fact that you don't understand the way multipart works. For your client-side code to work, i.e form-data to be sent back to the backend, you need to:
Either remove the header and let the browser choose the header for you based on your data type
Or when using 'Content-Type': 'multipart/form-data', add a boundary to it
Multipart boundary looks like this,
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryABCDEFGHIJKLMNOPQRSTUVWXYZ'
Simply doing the following will solve the issue for you as the browser will take care of the headers needed.
axios.post('your-server-url', data).then(....)