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.
Related
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.
I am trying to download a file when a user clicks on a particular button. This file is an image which gets created when the said button is pressed. What I want is, it should automatically download the image on the client's device.
I am using Flask on the server code, and ideally, the send_file function of Flask should trigger this auto download as it adds the Content-Disposition header.
On the client side, I have a JS code which uses fetch API to send a POST request to the server with some data, which is used for generating the image which is to be downloaded.
This is the JS code:
function make_image(text){
const json={
text: text
};
const options={
method: "POST",
body: JSON.stringify(json),
headers:{
'Content-Type':'application/json',
}
};
fetch('/image',options)
.then(res=>{
res.json(); //Gives an error: Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
}).catch(err=>console.log(err));
}
And this is the Python code on the server:
#app.route('/image',methods=['POST'])
def generate_image():
cont = request.get_json()
t=cont['text']
print(cont['text'])
name = pic.create_image(t)
time.sleep(2)
return send_file(f"{name}.png",as_attachment=True,mimetype="image/png")
But nothing is happening. The image doesnt get downloaded. However,the image is getting created on the server and is not corrupt
How do I resolve this? And is there some other way to do what I am trying to do?
You can do the below
return send_from_directory(dir, file_name, as_attachment=True)
This will download the file on the user's machine.
Edit:
BTW, if you create an html form like below, you do not need javascript.
<form action='action here' method='post'>
<input type='submit'>
</form>
As #clockwatcher mentioned a different question, I used the download.js module to handle the download of the image.
So my JS code looks like this now:
function make_image(text){
const json={
text: text
};
const options={
method: "POST",
body: JSON.stringify(json),
headers:{
'Content-Type':'application/json',
}
};
fetch('/image',options)
.then(res=>{
return res.blob();
}).then(blob=>{
download(blob)
}).catch(err=>console.log(err));
}
And an addition to the script tag in the html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/downloadjs/1.4.8/download.min.js"></script>
With no change in the Python server code.
It works now
I would like to do create a tempermonkey script that would download a file on a site without bothering the user with saving it on the disk. So the file would be stored in a variable, which the script would be able to use to upload that file to my remote server.
Is it possible to do in browser javascript?
Diagram:
One option would be to download the file as a blob using fetch:
async function upload() {
const res = await fetch('https://example.com/download-endpoint')
const blob = await res.blob()
fetch('https://example.com/upload-endpoint', {
method: 'POST',
headers: {
'Content-Type': blob.type
},
body: blob
})
}
I am currently developing a Sketch Plugin, where an image gets sent to the Microsoft Custom Vision API for object detection.
The Sketch Plugin itself is written in Javascript, a fs polyfill and a fetch polyfill is available. An API call with an image url works perfectly fine. However, I have trouble sending a local file from my computer as I am not 100% how I can access it.
var templateUrl = require('../assets/test.png').replace('file://', '');
var file = fs.readFileSync(templateUrl);
var request = postData('https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/XXXXXXX/image');
request.then(data => data.json()).then(data => myFunction(data));
// post request with file
function postData(url, data) {
return fetch(url, {
method: 'POST',
headers: {
'Prediction-Key': 'XXXXXXXXXX',
'Content-Type': 'application/octet-stream',
},
body: file,
})
}
Does anyone have experience with sending local files to the image recognition API? Any help would be very much appreciated!
Thanks in advance!
Best, C
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(....)