How Can I save a blob file with a form submission using React.js + Django Rest Framework

Asked
Active3 hr before
Viewed126 times

7 Answers

usingreact
90%

Now that the file is added to the form submission the server returns a 400 error.,The form was submitting fine without the file and saving in django without the code for the file added.,Connect and share knowledge within a single location that is structured and easy to search.

you should send it as "Content-Type": "multipart/form-data" to django imageField. So you should convert your blob file appropriately:

let cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
let arr = this.cropImg.split(","),
   mime = arr[0].match(/:(.*?);/)[1],
   bstr = atob(arr[1]),
   n = bstr.length,
   u8arr = new Uint8Array(n);

while (n--) {
   u8arr[n] = bstr.charCodeAt(n);
}

let imageCrop = new File([u8arr], 'imagename', {
   type: mime
});

const fd = new FormData();
fd.append("avatar", imageCrop);

// send fd to axios post method. 
// You should pass in post request "Content-Type": "multipart/form-data" inside headers.
88%

Now while in the react-form-data directory, run the following commands: ,React: We will be using React to build the UI components for our form. I presume by now you understand the conecpt of React and what it is.,above all others. Your middlewares should look like these:

#cmd

mkdir react - form - data && cd react - form - data
load more v
72%

Going full JSON in an API has a couple of benefits over working with urlencoded form data (shared input and output formats, easier to work with complex data hierarchies, less verbose, etc). There are, however, a couple of pitfalls. Working with file uploads in JSON APIs is one of those things that often cause confusion and can lead to bikeshedding.,It’s a little bit of extra work, and it might – depending on your data layout – require you to prune resources that do not have their binary assets attached within some period of time, but it is quite pleasant to document and work with.,Encode the binary data (e.g. Base64) and pass it as a value of a key in the JSON document. There are a couple of drawbacks with this approach: it increases the size of the uploaded files, reduces API output readability, prevents servers from streaming files to disk, and the encoding/decoding adds processing overhead.

from django.db
import models

class Profile(models.Model):
   name = models.CharField(max_length = 200)
bio = models.TextField(blank = True)

pic = models.ImageField(upload_to = 'pics', blank = True)

updated_at = models.DateTimeField(auto_now = True)
created_at = models.DateTimeField(auto_now_add = True)
load more v
65%

REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types., Ordering of renderer classes ,Rest Framework Latex provides a renderer that outputs PDFs using Laulatex. It is maintained by Pebble (S/F Software).

Pretag
 Pretag team - issue, fix, solve, resolve
75%

Of course we can use Axios to send files to a server and vice-versa so let’s see a small snippet where we upload a Blob file by using FormData API:,It is very common for a javascript engineer to handle xhr requests where Blobs are involved in his/her daily routine. Many applications let the user to upload or download files and this is where an HTTP client comes into play.,The tricky part here is that we need to specify that we are sending FormData in the Request Headers. The response will be in JSON format as it is specified in Axios by default.

Nothing fancy here. We are dispatching some actions and we show a message accordingly. If we don’t get a proper response from our API maybe because of a timeout issue or sth, then we will show a dummy message:

alert('Something went wrong while uploading this file');
load more v
40%

upload(file): POST form data with a callback for tracking upload progress,We use selectedFiles for accessing current File as the first Item. Then we call UploadService.upload() method on the currentFile with a callback. So create following upload() method:,Or: Spring Boot Multipart File upload (to database) example

Pretag
 Pretag team - issue, fix, solve, resolve
22%

On saving, create-react-app will instantly refresh the browser.,Again, create-react-app will instantly refresh the browser and you’ll see the result,Store the file in state, and only upload when a user clicks the upload button.

Pretag
 Pretag team - issue, fix, solve, resolve

Other "using-react" queries related to "How Can I save a blob file with a form submission using React.js + Django Rest Framework"