Trouble with uploading csv file via API

New to Nocodb and can’t figure out how to upload a csv to the DB via API.

Can anyone see anything wrong with my code?

Please help! Any advice appreciated!

try {
            // Step 1: Upload file to storage
            const formData = new FormData();
            formData.append('file', file);
    
            const storageResponse = await fetch(`${process.env.NEXT_PUBLIC_NOCODB_API_URL}/api/v1/db/storage/upload`, {
                method: 'POST',
                body: formData,
                headers: {
                    'xc-token': process.env.NEXT_PUBLIC_NOCODB_AUTH_TOKEN
                }
            });
    
            if (!storageResponse.ok) {
                throw new Error(`Failed to upload file to storage: ${await storageResponse.text()}`);
            }
    
            const storageData = await storageResponse.json();
    
            // Step 2: Update user record with file information
            const fileInfo = {
                url: storageData.url,
                fileName: file.name,
                mimetype: file.type,
                size: file.size.toString()
            };
    
            const updateResponse = await fetch(`${process.env.NEXT_PUBLIC_NOCODB_API_URL}/api/v2/tables/m0ebqzut70q4sus/records/${userId}`, {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'xc-token': process.env.NEXT_PUBLIC_NOCODB_AUTH_TOKEN
                },
                body: JSON.stringify({
                    Uploaded: JSON.stringify([...uploaded, fileInfo])
                })
            });

@bf7051 Are you trying to upload a CSV file into a field of type attachment in a record? Or upload records to a table via API?

If its former, you can find details here

Upload API response will be an array of uploaded files so storageData.url should be storageData[0].url

1 Like

@pranavxc Ah I see what I was doing wrong. Here’s the fix:

try {
        // Step 1: Upload file to storage
        const formData = new FormData();
        formData.append("file", file);
        formData.append('json', JSON.stringify({
          "api": "xcAttachmentUpload",
          "project_id": process.env.NEXT_PUBLIC_PROJECT_ID,
          "dbAlias": "db",
          "args": {}
        }));
  
        const storageResponse = await fetch('https://app.nocodb.com/api/v1/db/storage/upload', {
          method: 'POST',
          body: formData,
          headers: {
            'xc-token': process.env.NEXT_PUBLIC_NOCODB_AUTH_TOKEN
          }
        });
  
        if (!storageResponse.ok) {
          throw new Error(`Failed to upload file to storage: ${await storageResponse.text()}`);
        }
  
        const storageData = await storageResponse.json();
        console.log('Storage response data:', storageData);
  
        // Ensure either url or path is present
        if (!storageData[0]?.url) {
          throw new Error("Attachment object must contain a url");
        }
  
        // Step 2: Update the existing user record with the new file
        const newAttachment = {
          id: storageData[0].id, // Assuming the response contains a unique ID
          url: storageData[0].url,
          title: file.name,
          mimetype: file.type,
          size: file.size,
        };

Next question then is how do I delete a file from a User? I added id: storageData[0].id, // Assuming the response contains a unique ID

to add an id to each upload, but since the files are just a data field within the User datatype, I don’t know how to reference them individually/uniquely… Any ideas??

Screenshot 2024-08-13 at 3.31.42 PM

Hi @bf7051,

I wanted to clarify a few key points regarding how attachments are handled:

  • Attachments are stored as JSON array of objects in cells, you are expected to use full object returned from storage/upload API on this array to avoid unexpected behavior.
  • There is an id for each attachment but it is used for internal referencing you can’t provide a custom one and even if you do so it would be overriden. Also note that it will be different for each reference of attachment (aka. copy&paste cell or duplicate table etc.)
  • There is no way to access or individually manipulate attachments using our API yet
  • In order to delete an attachment you can simply remove it from JSON array and update the cell
  • After deletion your existing urls might be available for 2~ hours as they are signed links, after that period it will not be possible to access that url

I hope this clears up any confusion. Let me know if you have any further questions!

1 Like

@mertmit that helps, but I have a question.

So I have a seperate table to hold the uploads data type. The table has an attachment field, name, and the system Id fields.

Im using the DELETE ’ /api/v1/db/data/{orgs} /{projectName} /{tableName} /{rowId}’ of which {rowId} is correctly referring to the upload entry’s system Id and the entry is successfully deleted in my db but…

UploadedNav.js:109 
 DELETE https://app.nocodb.com/api/v1/db/data/wle184gq/pbw8ynuqku5hxok/mihztn2qgl1gedc/100 400 (Bad Request)

any idea why I’m getting this error in my console?

@bf7051 this seem to be a bug.

Fix PR is ready here fix: Row delete bug by pranavxc · Pull Request #9319 · nocodb/nocodb · GitHub

So this should be fixed on our next release. Thank you for patience.

2 Likes