Quiero guardar el pdf en Cloudant. Con el siguiente código, aparece un error al abrir el archivo adjunto en Cloudant. "Se encontró un error al procesar este archivo" Puedo poner datos de cadena falsos en el campo "._attachments[name].data" y se guardará.
Los documentos de Cloudant dicen que el contenido de los datos debe estar en base64 y eso es lo que estoy intentando. Cloudant dice "El contenido debe proporcionarse mediante el uso de la representación BASE64"
function saveFile() { var doc = {}; var blob = null; //fileName is from the input field model data var url = fileName; fetch(url) .then((r) => r.blob()) .then((b) => { blob = b; return getBase64(blob); }) .then((blob) => { console.log(blob); let name = url._rawValue.name; doc._id = "testing::" + new Date().getTime(); doc.type = "testing attachment"; doc._attachments = {}; doc._attachments[name] = {}; doc._attachments[name].content_type = "application/pdf"; doc._attachments[name].data = blob.split(",")[1]; console.log("doc: ", doc); }) .then(() => { api({ method: "POST", url: "/webdata", auth: { username: process.env.CLOUDANT_USERNAME, password: process.env.CLOUDANT_PASSWORD, }, data: doc, }) .then((response) => { console.log("result: ", response); alert("Test has been submitted!"); }) .catch((e) => { console.log("e: ", e); alert(e); }); console.log("finished send test"); }); } function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); }¿algunas ideas? Gracias
CouchDB, y por extensión Cloudant, tiene un medio para manejar una solicitud de "varias partes" donde el documento JSON y los archivos adjuntos se envían en la misma solicitud. Consulte https://docs.couchdb.org/en/3.2.2/api/document/common.html#put--db-docid
Están modelados en el proyecto Nano de CouchDB aquí: https://www.npmjs.com/package/nano#multipart-functions
const fs = require('fs'); fs.readFile('rabbit.png', (err, data) => { if (!err) { await alice.multipart.insert({ foo: 'bar' }, [{name: 'rabbit.png', data: data, content_type: 'image/png'}], 'mydoc') } });Alternativamente, puede escribir el documento primero y agregar el archivo adjunto en una solicitud complementaria. Usando los SDK de Cloudant actuales:
const doc = { a: 1, b: 2 } const res = await service.putDocument({ db: 'events', docId: 'mydocid', document: doc }) const stream = fs.createReadStream('./mypdf.pdf') await service.putAttachment({ db: 'events', docId: 'mydocid', rev: res.result.rev, // we need the _rev of the doc we've just created attachmentName: 'mypdf', attachment: stream, contentType: 'application/pdf' })Descubrí que estaba haciendo demasiado con el archivo PDF. No es necesario hacer blob y luego convertir a base64.
Solo convierte a base64.
async function sendFiles() { try { const url = fileName; const doc = {}; doc._attachments = {}; doc._id = "testing::" + new Date().getTime(); doc.type = "testing attachment"; for (let item of url._value) { const blob2 = await getBase64(item); let name = item.name; doc._attachments[name] = {}; doc._attachments[name].content_type = item.type; doc._attachments[name].data = blob2.split(",")[1]; } const response = await api({ method: "POST", url: "/webdata", data: doc, }); } catch (e) { console.log(e); throw e; // throw error so caller can see the error } console.log("finished send test"); fileName.value = null; } function getBase64(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); }); }Esto funciona para mí.