-
How can I upload and attach image to a row using REST API? |
Beta Was this translation helpful? Give feedback.
Replies: 13 comments 9 replies
-
It can be done in two steps
|
Beta Was this translation helpful? Give feedback.
-
Could you please tell me how to upload image/file using QraphiQL? @pixplix |
Beta Was this translation helpful? Give feedback.
-
Hi @o1lab I am trying to recreate the JS code in Python:
I get:
Am I creating the proper endpoint? |
Beta Was this translation helpful? Give feedback.
-
@IvanCharcos Following code may help, headers = {"xc-token": "<token>"}
print("File Exists: ", invoiceFile)
## Add invoice
invoicePayload = {
"json": (None, json.dumps({"api": "xcAttachmentUpload", "project_id": "auto_6avb", "dbAlias": "db", "args": {}}), 'application/json'),
"file": ('finlename.pdf', open(invoiceFile, 'rb'), 'application/octet-stream')
}
params = {"project_id": "auto_6avb"}
r = requests.post(root + addFile, files=invoicePayload, headers=headers, params=params)
attachments = r.json() |
Beta Was this translation helpful? Give feedback.
-
I had some difficulties to upload a picture from windows. You can use my scripts as example to upload a picture to a table. |
Beta Was this translation helpful? Give feedback.
-
This thread provided me with some good guidance. I thought I would share a Python snippet to help others get on the right path to uploading multiple files and attaching them to a nocodb record. import json
import requests
## File (multi) upload
count = 0
filelist = ["test1.txt", "test2.txt"]
headers = {
"xc-auth": "AUTH_TOKEN"
}
params = {
"project_id": "test_project_01_b9o9"
}
for file in filelist:
print (file)
print (count)
files = {
"json": (None, json.dumps({"api": "xcAttachmentUpload", "project_id": "test_project_01_b9o9", "dbAlias": "db", "args": {}}), 'application/json'),
"file": (file, open(file, 'rb'), 'application/octet-stream')
}
r = requests.post(
f"https://nocodb.foo.bar/dashboard/",
files=files,
headers=headers,
params=params
)
print(r.status_code)
print(r.text)
if count == 0:
json2string = str(r.json())
jsonString = json2string.replace("'", '\"').replace('\n', '\\n')
else:
appendJsonString = jsonString
json2string = str(r.json())
jsonString = json2string.replace("'", '\"').replace('\n', '\\n')
jsonString = f"{appendJsonString},{jsonString}"
count += 1
jsonFilePayload = (f"[{jsonString}]")
print (jsonFilePayload)
## Add record to table and file(s) as attachments
headers = {
"xc-auth": "AUTH_TOKEN",
'Content-Type': 'application/json'
}
url = "http://nocodb.foo.bar/nc/test_project_01_b9o9/api/v1/Table01"
payload = json.dumps({
"title": "foo",
"file": jsonFilePayload
})
r = requests.request("POST", url, headers=headers, data=payload)
print (r.status_code)
print(r.text) |
Beta Was this translation helpful? Give feedback.
-
I'm sorry for the silly question, but where are the docs for this? I can't find them. I see the swagger defs for my database-specific endpoints, but that doesn't cover attachment upload... Or - does anyone at least have a working example in Postman? Best I could get is 403 with a body of
(It's not an issue of a bad auth token, I've checked.) |
Beta Was this translation helpful? Give feedback.
-
@zblesk i use js script, it work: var fs = require('fs');
var axios = require('axios');
var FormData = require('form-data');
var image_path = "/home/user/example.jpeg";
const nocodb_token = XXXXXXXXXXXXXXXX;
const project_id = 'XXXXXXXXXXXXXXXX';
function insertImage (image_path, callbackOK, callbackError) {
const formData = new FormData();
formData.append("file", fs.createReadStream(image_path));
formData.append('json', JSON.stringify({"api":"xcAttachmentUpload","project_id":project_id,"dbAlias":"db","args":{}}));
axios({
url: 'http://10.0.0.1:8080/dashboard',
data: formData,
headers:{
'Content-Type':`multipart/form-data; boundary=${formData.getBoundary()}`,
'xc-auth': nocodb_token
},
method: 'post',
params: {"project_id":project_id}
})
.then(function (response) {
// handle success
//console.log(response.data);
return callbackOK(response.data);
})
.catch(function (error) {
// handle error
//console.log(error);
return callbackError(error);
})
} |
Beta Was this translation helpful? Give feedback.
-
Thanks. In case someone else is also trying in a different language, here is the raw request that the code above generated:
|
Beta Was this translation helpful? Give feedback.
-
Hi all! |
Beta Was this translation helpful? Give feedback.
-
This is the latest template for uploading attachments into a specified row (creating a new row) written in Python
|
Beta Was this translation helpful? Give feedback.
-
Uploading a file to Attachment field type can be done in 2 steps
Updated JS code here gives a sample for new record insertion case const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
(async () => {
// API Token for uploading the file
// Reference : https://docs.nocodb.com/account-settings/api-tokens/#create-api-token
const apiToken = '3WDl0GloFP-B01fNghspJx98AX_4ct4uLMvCHqWU';
// Base URL for the API
const baseURL = 'https://app.nocodb.com';
// Base ID of the table
// Base ID of a table can be retrieved from the URL (OR) by using base context menu from the left side bar project tree
const baseID = 'm7wp2q8n4d9w4kp';
// Read the image file
const photoStream = fs.createReadStream('./photo.png');
// Create form data
const formData = new FormData();
formData.append('file', photoStream);
// Define headers for uploading the file
const uploadHeaders = {
'xc-token': apiToken,
...formData.getHeaders(),
};
// Upload the file
const uploadResponse = await axios.post(`${baseURL}/api/v1/db/storage/upload`, formData, {
headers: uploadHeaders,
});
// Create a new row in the database
const response = await axios.post(`${baseURL}/api/v2/tables/${baseID}/records`, {
// Example field data
"Title": "New Name",
// Pass the uploaded file data; file is field name here & its type is "Attachment"
"file": uploadResponse.data,
}, {
headers: {
'xc-token': apiToken,
'Content-Type': 'application/json',
},
});
})().catch(err => {
console.log(err);
}); |
Beta Was this translation helpful? Give feedback.
It can be done in two steps
Upload the image using our meta API which returns the public URL and other meta details.
Example in Javascript(with Axios)
Response will be: