Piero Pajares
Piero Pajares

Reputation: 277

how to get the file of an image? in python ? django rest framework

class DemoAPIView(APIView):
    parser_classes = (JSONParser, FormParser, MultiPartParser)

    def post(self, request, format=None):
        data = request.data
        attached_file = request.FILES['attached_file']
        description_image = data.get('descriptionImage', None)
        attachment = dict(object_id=174, project=1, attached_file=attached_file,
                          description=description_image)
        header = {'Authorization': 'Bearer eyJ1c2VyX2F1dGhlbnRpY2F0aW9uX2lkIjoxNn0:1gSTf6:KbOb0yhqC-qVPTEPRoiVBBZjN6M'}
        r = requests.post('demo/api/v1/issues/attachments', data=attachment, headers=header)
        print(r.json())
        return Response({'error': 'ERROR XD'}, status=status.HTTP_400_BAD_REQUEST)

and the error that the api booted me is the following:

{'attached_file': ['No file was submitted. Check the encoding type on the form.']}

which is the image that I sent from the client. print the attached file and just show me the url, apparently that's the problem. Is there any way to get the full file?

Form client:

const bodyFormData = new FormData();
            if (typeof this.image !== 'string') {
              bodyFormData.append('attached_file', this.image);
              bodyFormData.append('descriptionImage', this.descriptionImage);
            }
            this.axios.post('/api/', bodyFormData,
              { headers: { 'Content-Type': 'multipart/form-data' } })
              .then((response) => {
                this.isSending = false;
                this.$snackbar.open(response.data.results);
                this.feedback = {};
                this.image = {};
              }).catch((err) => {
                this.$snackbar.open({ message: err.response.data.error, type: 'is-danger' });
                this.isSending = false;
              });

Upvotes: 2

Views: 1933

Answers (2)

Rohan Kumar Mainali
Rohan Kumar Mainali

Reputation: 11

I was stuck on the similar problem. I used an simple technique to solve (Using PATCH instead of PUT) solved my problem.

Upvotes: 0

Thomas Matecki
Thomas Matecki

Reputation: 668

The submitted form probably is not enctype="multipart/form-data.

As stated in the Django docs:

Note that request.FILES will only contain data if the request method was POST and the that posted the request has the attribute enctype="multipart/form-data". Otherwise, request.FILES will be empty.

For DRF, you probably want the FileUploadParser(see this)

Upvotes: 1

Related Questions