Encountering Zip File Corruption Issue post MongoDB Download

My goal is to attach a zip file to an object and request the zip file when the object is called from the client. I was successful in uploading the zip file using the following code:

const upload = multer({
    fileFilter(req, file, cb){
        if (!file.originalname.match(/\.(html|zip)$/)) {
            return cb(new Error("Please upload a .html or .zip file"))
        }
        cb(undefined, true)
    }
})

router.post('/map/:id/file/upload/zip', auth, upload.single('zip'), async(req, res) => {
    try {
        const map = await Map.findOne({_id:req.params.id})
        if (!map) {
            return res.status(400).send({"message":"Map is not found in database"})
        }
        map.zipBuffer = req.file.buffer
        map.save()
        res.status(201).send(map)
    } catch (e) {
        res.status(500).send(e)
    }
})

Although the file saved successfully, when I tried to download it, I encountered the following error:

The archive is either in unknown format or damaged

Here is the code block I used to pull the zip file:

router.get('/map/:id/file/upload/zip', async(req,res) => {
    try {
        const map = await Map.findOne({_id:req.params.id})
        if (!map) {
            return res.status(400).send({"message":"No map found"})
        }
        const html = map.htmlBuffer
        res.set("Content-Type","application/x-zip-compressed")
        res.send(html)
    } catch (e) {
        res.status(500).send(e)
    }
})

I am seeking assistance on how to properly upload a zipped file and retrieve it without damaging the file.

Answer №1

Isn't it amusing that the solution to your query is staring right at you?

There seem to be some discrepancies in the following code snippets:

const html = map.htmlBuffer
res.set("Content-Type","application/x-zip-compressed")
res.send(html)

It appears that you are sending the file as an HTML buffer instead of the expected zip format.

Revise the code snippets above to match the correct format and everything should work smoothly.

Answer №2

Here's a different perspective on implementing a more versatile solution compared to destiny-ajakaiye's response. You could consider using the following code snippet:

res.set("Content-Type", map.contentType)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Struggling with converting 11-line toy neural network code into JavaScript

I'm preparing to deliver a brief presentation on neural networks this coming Tuesday to my fellow web developer students. My plan was to convert this code (found under Part 1, a tiny toy neural network: 2 layer network) into JavaScript so that it woul ...

In search of an explanation for why Promise outcomes for an inline function are not resolving to the desired return value

I have been exploring JavaScript promises and encountered an issue while trying to consolidate promise logic from separate functions into a single inline function. Combining everything into one inline function is causing the return result of the promise to ...

Issue with implementing setTimeout on await fetch() result

I'm trying to figure out how to add a setTimeout to my request response when using await fetch. Currently, each response is being sent to a DIV in the HTML, but I want to introduce a delay of 5 seconds before each response appears. I attempted this s ...

What steps can I take to make sure that a sub component's props are refreshed properly?

I'm encountering an issue with RTK queries in my project. I have a parent component that contains a table component. When a refresh event occurs, such as deleting data, the parent component receives updated data and passes it down to the child compone ...

Calculating the total value of individual sections using Jquery

I have multiple sections, each containing three input fields: <div class="product_quantity"> <div class="color-quantity"> <input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text"> ...

Utilizing Jquery to enhance slide image transitions with navigational links

As a newcomer to jQuery, I am attempting to create a slider using jQuery. Here is the script I have so far: $(function() { var bgCounter = 0, text = [ 'some html code here', 'some html code here', 'some ...

position: absolute is only applying to the initial item

I have a user card component with a menu button at the top that should display a menu when clicked. The issue I'm facing is that when I click on the menu button of the other user cards, the menu still shows on the first card instead of the one I click ...

How to eliminate duplicate items in an array and organize them in JavaScript

I am looking to eliminate any duplicate items within an array and organize them based on their frequency of occurrence, from most to least. ["57358e5dbd2f8b960aecfa8c", "573163a52abda310151e5791", "573163a52abda310151e5791", "573163a52abda310151e5791", "5 ...

Clicking on the checkbox will trigger an AJAX request to cache the

Encountering a problem with an old system I am currently updating: In the <div id='list'>, there is a checkbox list. Upon clicking a checkbox, it triggers an ajax request that returns JavaScript to execute. The JavaScript in the Ajax requ ...

I have a single object within the user array of IDs in MongoDB. My goal is to perform an aggregation lookup for those IDs in order to retrieve the related users' details

{ "_id": "61efc2c437c455b7216629ff", "event_images": [ "1643102858880rn_image_picker_lib_temp_38cdc02f-4207-446a-9263-1e6914954095.jpg" ], "distance": 80, ...

"Injecting the value of a jQuery variable into a PHP variable

<script type="text/javascript"> $(document).ready(function(){ $("#t_select").change(function(){ var table_name = $("#t_select").val(); $.ajax({ type: 'POST', ...

What is the reason for the num pad being classified as a character?

Everything is functioning correctly, but when I use the number pad on the right side of my keyboard, it registers as a character and gets deleted. However, the numbers on the left side are accepted without any issue. I want to be able to input numbers usin ...

When selecting an input within a div, the Angular onblur function is behaving erratically

How can I prevent the div from closing when I click on an input inside it after setting a tabindex to the div and closing it on blur? Solution for app.component.html: <button (click)="openToggle('toggle1')">Toggle 1</button> ...

Add an element to the input field

Two input buttons are available for users to upload files. <input type="file" id="fileUpload" name="files" multiple><br/> <div id="selectedFiles"></div> The selected files will be appende ...

Align content distributed evenly will not display a division

I am currently using React to code and learning by doing so. I have two different images displayed, each followed by a div element with a height of 20px and a brown background color. I have set the height to "100%" and justifyContent to "space-between", bu ...

problem | JQuery slide causing automatic page scroll to top

Here is the HTML for my slide: <div class="slide_container"> <div class="one_slide"> <a href="#"><img alt="slide_img" class="slide_img img-responsive" src="images/slide2.jpg"></a> </div> ...

Received TypeError: Unable to call reset function - issue clearing input field post ajax request

Having Trouble Clearing Input Fields After AJAX Request: $.ajax({ type: "POST", url: "river_flow.php", data: { username: $("#username").val(), idv:$("#idv").val(), comment: $("#comment").val()}, cache: false, success: function(da ...

Assign a specific value to each object

Receiving data from the backend in a straightforward manner: this.archiveService.getRooms(team).subscribe( res => { this.form = res; this.form.forEach(el => { el.reservation.slice(-6).match(/.{1,2}/g).join('/'); }); }, ...

I must modify the initial statement to appear in bold from the paragraph with the use of JavaScript and CSS

Mr. XYZ and Mrs. ABC are known for their integrity. They own a stylish car. In the next paragraph, I would like to emphasize the first sentence by making it bold, We admire our exceptional leader J.K.L. He shows great potential. In this section, I wan ...