What is causing the corruption of the .docx file returned by the Controller?

I am working on a .NET Core 2.2 web application. In one of my Controller methods, I perform editing tasks on a Word document and then send it back to the client. However, when I try to view the document on the client side, I encounter this dialog:

https://i.sstatic.net/NeNxR.png

I have attempted different approaches to solve this issue. Below is a snippet of the controller method (some earlier attempts are commented out!)

byte[] byteArray = System.IO.File.ReadAllBytes(compositeFileName);
//MemoryStream content;

//content = new MemoryStream(byteArray);
//string contentType = "application/octet-stream";
//return File(content, contentType, compositeFileName);
//return File(byteArray, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", compositeFileName);
return new FileContentResult(byteArray, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");

Here's the JavaScript code (from a vue.js file)

self.$http
    .post('/MyController/MyMethod', myData, self.IENoCacheHeaders)
    .then(function (response) {
         var blob = new Blob([response.body], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
         var link = document.createElement('a')
         link.href = window.URL.createObjectURL(blob)
         link.download = 'test.docx'
         link.click()

After inspecting the contents of response.body, I found a significant amount of binary data. I have tried switching between MIME types such as application/vnd.openxmlformats-officedocument.wordprocessingml.document and application/octet-stream but with no success.

If anyone can provide insight into what might be causing this issue, please let me know. The file being streamed back to the browser (compositeFileName points to a .docx file on the server) appears to be fine on the server - the problem seems to occur during the streaming and processing on the client side.

Thank you

Edward

Answer №1

I found a way to streamline my strategy:

axios
.post('/MyEndpoint/MyFunction', dataToSend, { responseType: 'blob' })
.then(function (res) {
     var downloadableLink = document.createElement('a');
     downloadableLink.href = window.URL.createObjectURL(res.body);
     downloadableLink.download = 'sample.docx';
     downloadableLink.click();

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

Using Multer: Specifying multiple destinations with the destination property

I am facing a situation where I have to store images in multiple directories. To achieve this, I have configured multer as follows: app.use(multer({ dest: path.join(__dirname, '`public/assets/img/profile`'), rename: function (fieldname, ...

Why do I keep encountering a null window object issue while using my iPhone?

Hey there! I've got a React game and whenever the user loses, a new window pops up. const lossWindow = window.open( "", "", "width=500, height=300, top=200, left = 200" ); lossWindow.document.write( & ...

Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements: $(".Element ...

Make sure to save your data prior to using req.session.destroy() in Express

Before destroying the session in the logout route, I need to save the session value "image location" into the database. Here is the solution I have implemented: app.get('/logout',function(req,res){ Person.update({ username: req.session.use ...

Dealing with Class and Instance Problems in Mocha / Sinon Unit Testing for JavaScript

Currently, I am working on unit testing an express middleware that relies on custom classes I have developed. Middleware.js const MyClass = require('../../lib/MyClass'); const myClassInstance = new MyClass(); function someMiddleware(req, ...

After entering just one character, the focus on the input field in Vue.js is lost

Currently, I am facing an issue with a view that contains an input field. When a character is entered, the input field loses focus, requiring an additional click to resume typing. Does anybody have any insight into what might be causing this problem? Here ...

Utilizing functions as parameters and implementing a flexible number of arguments

I have two different functions: Function called 'first' which takes 1 argument Another function called 'second' that takes 2 arguments Next, there is a third function that accepts a function and a value as its parameters. I am strugg ...

Creating a Popup with a Hazy Background: A Step-by-Step Guide

I've been working on implementing a popup on my existing page that opens 4.5 seconds after the page loads. I want to add a blur effect to the background when the popup appears. I've tried various methods to add the blur effect to the main div, bu ...

Distributing information to modules made of Polymer

Is there a way to create a single source for all data that my elements can utilize but not change (one-way data-binding)? How can I achieve this without using a behavior? I attempted the following in my code: <script type="text/javascript" src="/data. ...

Creating a div overlay triggered by the addition of a child tag

Using the Paypal zoid feature, I have a button that opens an iframe in the parent div when clicked. However, the iframe causes the other contents of the website to shift around, making it look messy. I'm wondering if there is a way to make the parent ...

Refreshing Vue by reloading new components and injecting them into the HTMLDOM

Is there a way to make Vue re-initialize itself after inserting a component fetched from an API into the DOM? The component looks like this: <div><My_component /></div> This component is part of a back-end snippet. When inserting it i ...

Stream video files using NodeJS and seamlessly switch between audio tracks

I am looking to stream a video on my PC through a browser using nodejs. I found a helpful guide on how to achieve this using express, which can be found at this link: https://medium.com/better-programming/video-stream-with-node-js-and-html5-320b3191a6b6 (P ...

Displaying mysqli results within a div while incorporating an onclick event for a javascript function that also includes another onclick event for a separate javascript function

I'm struggling to figure out the correct way to write this script. Can someone please guide me in the right direction or suggest an alternative method? I've searched but haven't found any relevant examples. I am fetching information from a ...

How can we ensure successful validation using Jquery?

I'm currently working on a basic form that includes text fields. Whenever these text fields are modified, an Ajax function is called to save the changes. However, I am facing a challenge in validating these fields using jQuery before the change even ...

The file type stored in Firebase storage is identified as 'octet-stream' rather than the expected 'png/jpg' format

I am experiencing an issue with uploading images to Firebase storage. After uploading them, I notice that they are labeled as application/octet-stream instead of the expected types like image/jpeg or image/png. Below is the code snippet I am using: <in ...

Modify the characteristic of a moving component provided it meets the criteria

One of my functions, 'refreshDisplay', is designed to generate dynamic elements. However, there is a specific condition that needs to be met. In the 'src' attribute of the image, I need to check if the obj.picture.thumbnail starts with ...

Tips for Adding For Loop Value to an Array in JavaScript

Trying to Add For Loop Value to an Array My Current View <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script> <style> body { font-family: Roboto, sans-serif; } #chart { max-width: 650px; margin: 35px auto; ...

Tips for clearing fields and displaying a success message after submitting a form with Vue.js

I am a beginner in Vue.js and I am facing an issue with my form submission. Even though the data is being saved successfully, the form fields are not getting emptied after submitting and there is no success message displayed. Can someone please provide gui ...

Automatically populate email fields with pre-filled form data

Looking to create an HTML form that utilizes JS/jQuery (no PHP) to capture data from "subject" and "message" fields and send an email. The goal is for the client-side code to open the user's mail client, pre-fill the subject and body with form data, a ...

Is it necessary to mock the HTML5 audio element when unit testing with Jest in vue.js?

Exploring the functionality of an AudioPlayer vue component that includes the HTML5 element, I am contemplating how to structure my specifications using Jest. template <audio id="player" ref="player" @ended="ended" @canplay="canPlay" :src="file"& ...