I am trying to send a zip file to my VUE app using laravel API endpoint so far the laravel controller when tested on Postman returns the zip file in binary correctly:
public function getZipFile()
{
try {
$id = request('id');
$zipURL = MarketPlace::select('zip_urls')->where('id', $id)->first();
$url = $zipURL->zip_urls;
$position = strpos($url, '/storage/CodeSources/');
$new_zip_link = substr($url, $position);
$filePath = public_path($new_zip_link);
if (file_exists($filePath)) {
$headers = [
'Content-Type' => 'application/zip',
'Content-Disposition' => 'attachment; filename="' . basename($filePath) . '"',
];
return response(file_get_contents($filePath), 200, $headers);
} else {
// Handle the case when the file is not found.
return response()->json(['error' => 'Zip file not found'], 404);
}
} catch (\Throwable $th) {
return response()->json(['error' => $th->getMessage(), 'line' => $th->getLine()]);
}
}
This is the route for the method:
Route::post('/get-zip-by-id', [CodeBuilder::class, 'getZipFile']);
However I can't seem to get the file in correct format so that I can manipulate it using jszip library and I'm getting this error:
Error: Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html
Here is my axios method to fetch the file:
async getTheZipFile() {
try {
const response = await axios.post('/get-zip-by-id', { id: this.id }, { responseType: 'arraybuffer' });
// console.log(response);
const arrayBuffer = response.data;
// console.log(arrayBuffer);
const uint8Array = new Uint8Array(arrayBuffer);
// console.log(uint8Array);
const zip = await JSZip.loadAsync(uint8Array);
this.files = await this.extractZipContents(zip);
// console.log(this.files);
} catch (error) {
console.log(error);
}
},
async extractZipContents(zip) {
const files = [];
await Promise.all(
Object.keys(zip.files).map(async (filename) => {
const fileData = await zip.files[filename].async('string');
files.push({ name: filename, content: fileData });
})
);
return files;
},
I tried changing the responseType to blob but didn't work.
Any suggestions will be helpful.