I’m writing a NextJS app that uploads an excel document (.xlsx), changes some rows, then allows the user to download the amended version.
I am testing out the upload/download functionality, and while the upload/download happens with the code below – the downloaded file is corrupted but the same size. It cannot open properly.
I am stuck and open to help.
Thanks.
/api/doupload/route.js:
import { NextRequest, NextResponse } from 'next/server'
import ExcelJS from 'exceljs';
export async function POST(req) {
try
{
const data = await req.formData();
const file = data.get('file');
const workbook = new ExcelJS.Workbook();
const bytes = await file.arrayBuffer()
const buffer = Buffer.from(bytes)
await workbook.xlsx.load(buffer); // Load from buffer
const dbuffer = await workbook.xlsx.writeBuffer(); // Get the modified data as a buffer
const filename = 'modified_spreadsheet.xlsx';
const res = new NextResponse(dbuffer, {
status: 200,
headers: ({
"content-disposition": 'attachment; filename='+filename,
"content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
})
})
return res;
}
}
catch(e)
{
return NextResponse.json({"a": "0", "b": e.message})
}
}
Main.jsx:
const MainLoggedIn = () => {
const [downloadUrl, setDownloadUrl] = useState(null);
async function doit()
{
try
{
const formData = new FormData();
formData.set('file', selectedFile);
//SelectedFile is an input type="File" button and is e.target.files[0]
const configuration = {
method: "POST",
url: '/api/doupload',
withCredentials: true, // needed to stop CORS errors
data: formData
};
const response = await axios(configuration)
const modifiedSpreadsheetBlob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// Create a URL for the blob
const modifiedSpreadsheetUrl = URL.createObjectURL(modifiedSpreadsheetBlob);
setDownloadUrl(modifiedSpreadsheetUrl);
}
catch(err)
{
console.log("ERROR: "+err.message);
}
return (
<p>
<a href={downloadUrl} download="modified_spreadsheet.xlsx">
Click here to download the modified spreadsheet
</a>
</p>
)
};
export default MainLoggedIn;