I am trying to solve this problem:
I am building an app in NEXT.js where users should upload certain documents (pdf,docx,etc.). I need to store those documents inside SQL Server as blobs. I do not know how should I pass data content of selected file to the API. I tried to use arrayBuffer or convert it to text and then cast as varbinary but without any success. I probably need completely different approach on this but was not able to find anything useful to my particular situation. Thanks in advance!
async function filesUpload(e) {
e.preventDefault();
const file = e.target.file.files[0];
/** File validation */
if (!file.type.startsWith("application/pdf")) {
alert("Please select a valid document");
return;
}
const buffer = await file.arrayBuffer();
console.log(buffer)
console.log({DATA: await file.text()})
const endpoint = '/api/PostData/insertContractDoc';
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({DATA: await file.text()}),
}
//const response = await (await fetch(endpoint, options)).json()
return
}
And this is my API endpoint:
const sql = require('mssql');
const configOBJ = require('../../../components/configSQL.js');
export default async function getAll(req,res){
await sql.connect(configOBJ.confSQL).then(pool => {
console.log("insert into [CONTRACTDOCUMENTS] values(302,1,null,null,'adad',CAST("+ req.body.DATA+" AS VARBINARY(MAX)))")
let querySTR = "insert into [CONTRACTDOCUMENTS] values(302,1,null,null,'adad',CAST("+ req.body.DATA+" AS VARBINARY(MAX)))"
return pool.request().query(querySTR)
}).then(result => {
//console.log(result);
return res.status(200).json(result);
}).catch(err => {
// ... error checks
console.log(err);
return res.status(500).send(err);
})
}