Download attachments using Django from a web browser

Trying to send an image as an attachment.

This is the code I am using:

resp = FileResponse(open(fullImgPath, "rb"))
resp['Content-Disposition'] = 'attachment; filename="{}"'.format(os.path. basename(fullImgPath))
resp["Content-Type"]="image/%s"%('png' if fullImgPath.endswith('png') else 'jpeg')
return resp

The code works fine when downloading the file using requests. However, when downloading the file via web browsers (such as Chrome and Firefox), the file ends up being corrupted.

Here's how you can download the file using JavaScript in a browser:

$.get(requestUrl)
        .success(function(data, textStatus, request){
                SaveBlob(data, "1.jpeg", "image/jpeg")
            }
        })

function SaveBlob(blob, fileName, contentType) {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob([blob], { "type" : contentType }));
    a.download = fileName;
    a.dispatchEvent(new MouseEvent('click'));
}

The previous method was working perfectly, but today I noticed that the file I downloaded appears to be corrupt. However, the image file stored on the server seems to be normal.

What could be causing this issue?

Answer №1

It appears that Jquery does not have the ability to download file content as binary, resulting in corrupted images. While jquery may not support downloading as binary, you can utilize native xhr for this task:

function SaveBlob(blob, fileName, contentType) {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(new Blob([blob], {"type": contentType}));
    a.download = fileName;
    a.dispatchEvent(new MouseEvent('click'));
}

var oReq = new XMLHttpRequest();
oReq.open("GET", requestUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
    SaveBlob(oReq.response, '1.jpg', 'image/jpg')
};
oReq.send();

This method raises questions about how it was functioning correctly before.

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

Input for uncomplicated changing identifier

I am looking to create types for dynamic keys that will be of type number. I have two similar types defined as follows: type UseCalculatePayments = () => { totalPayments: number; aggregate: number; condition: boolean; }; type UseCalculateCommissio ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Jquery debugger keeps getting triggered multiple times by checkbox interactions

I've encountered an issue while working on Mvc.Grid that involves the onclick event of a checkbox. Within the grid, each row represents a Profile and contains a checkbox for selection. My goal is to retrieve a list of IDs corresponding to the checked ...

Setting up computed properties in VueJSSetting up computed values in

I am currently working on developing a lottery number service, and I am curious about how to set up computed properties. I came across the Vue.js documentation for computed properties at https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties. I tr ...

Using JavaScript to create an image slider

My image slideshow with prototyping is not working properly and I am struggling to fix it. I have tried binding the setInterval function but it's not working. I also attempted to wrap it, but that didn't work either. What should I do to solve thi ...

I'm encountering an issue with VUEJS components including my show route in their get call. How can I make my journals/:id pages function properly without encountering a Mime

I encountered a MIME type error stating: Refused to apply style from 'http://localhost:8080/journals/assets/css/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. ...

What is the best way to retrieve certain fields from a Firestore database using Next.js?

Is there a way to access a specific field in a document using the user's uid as its name? I am utilizing useAuthState from react-firebase-hooks to retrieve the user's credentials (uid). https://i.sstatic.net/t1xGL.png This code snippet allows me ...

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...

Personalize the req.body object in Nodejs

I'm curious to know if it's possible to customize the req.body that is sent to MongoDB. Currently, my req.body looks like this: { f_name: 'John', l_name: 'Doe', phone: '4521234892345' } However, I would like it ...

Tips for accurately measuring the height of a single table cell

I am facing an issue with a table that I have set up. Here is the code: <table> <tr> <td id='tdleftcontent' style='border:1px solid red;'> <asp:Label ID='lbl' runat="server"></asp:Label> < ...

Guide on eliminating lines that start with a particular character

I need help figuring out how to remove all lines of code that start with #include. Here's an example: #include 'utils/namespace.js' #include 'utils/constants.js' #include 'utils/helpers.js' #include 'utils/json2.js& ...

Oops! Invariant violation alert: Exceeded maximum re-renders. React is putting a cap on the number of renders to avoid getting stuck in an endless

Looking to implement a custom snackBar feature that displays a message upon user sign-in or sign-out events: SnackBar.jsx: import React from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import CheckCircleIcon from "@ma ...

javascript: comparing a specified time to determine if it is within a set time frame

In the process of developing the back-end for a fashion-related application using Node.js, I am faced with the task of indicating whether a particular store is open or closed based on the current time. How can I effectively compare the current time with ...

What are the best techniques for maintaining state in Xstate state machines within a React application?

I'm currently using a functioning cart state machine in reactjs to add items to the cart. However, I've noticed that when refreshing the page, the context is not persisted. As someone new to state machines, I would appreciate any assistance in fi ...

Commitment without anticipation of a resolution or rejection

While testing one of my AngularJs Services, I decided to write some Unit tests. Below is a sample code snippet that I have come up with: it('', function(done) { aDocument.retrieveServiceFile(extractedFileFeature) .then(function() { ...

Show the screen name of a user upon disconnecting from the server

When a user disconnects from the server, I want to display a message. Currently, the message is shown to all users, but I'm having trouble displaying the actual user's name. Instead, it shows the name of the connected clients to themselves. I&apo ...

Tips for using the identical function on matched elements

I am working on a code where I want each textbox input to change its corresponding image. The function is the same for all partners in the list (txt & img). I have looked around and found some similar posts, but I am struggling to make the function wor ...

issues arise post-transpilation with creating errors

In order to practice, I decided to create a basic TypeScript project. If it could be helpful, here is my ts.config: { "compilerOptions": { "target": "es2016", "module": "commonjs", "outDir": "./dist", "esModuleInterop": true, "forceC ...

Troubleshooting the issue with Django Twitter-bootstrap collapse functionality not functioning as expected

I've been attempting to implement a simple collapse feature in my Django project, but even after simplifying it, the functionality remains faulty. As a reference, I attempted to install jQuery using pip install django-static-jquery==2.1.4 and subsequ ...

What is the best way to transform the HTML retrieved from an AJAX GET request into an object using JQuery?

$.ajax({ method:"get", url:"/wall", data:"ajax=1", beforeSend:function(){}, success:function(html){ $("#grid_mason").append(html); //Inserting additional co ...