简体   繁体   中英

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

I am trying to submit a cropped an image generated in a react app using react-image-crop,and save it to a Django Rest Api using Axios.

The app uses React, Redux and Axios on the frontend and Django Rest Framework on the backend.

The form was submitting fine without the file and saving in django without the code for the file added.

Now that the file is added to the form submission the server returns a 400 error.

I suspect that I am not submitting the blob in the correct format to the django server, but I am unsure on how to proceed.

Update: I have used axios below to convert the blob url to a blob and now I am trying to a file that I can submit to a django rest api. The form submits to the django rest API without the file, but when the file is add into the form submission, I receive a 400 error. I have Updated the code to reflect my latest integrations. I have included the code where I set the headers to multipart/form-data. The error seems to be in the file conversion process in the onSubmit() method below.

Here is my relevant code: Importing the react-image-crop library.

// Cropper
import 'react-image-crop/dist/ReactCrop.css';
import ReactCrop from 'react-image-crop';

Function inside of a react hook:

const AdCreator = ({ addFBFeedAd }) => {
  const [title, setTitle] = useState('');
  const [headline, setHeadline] = useState('');
  const [ad_text, setAdText] = useState('');
  const cropper = useRef();



  // Cropper
  const [upImg, setUpImg] = useState();
  const imgRef = useRef(null);
  const [crop, setCrop] = useState({ unit: '%', width: 30, aspect: 1.91 / 1 });
  const [previewUrl, setPreviewUrl] = useState();

  const onSelectFile = e => {
    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.addEventListener('load', () => setUpImg(reader.result));
      reader.readAsDataURL(e.target.files[0]);
    }
  };

  const onLoad = useCallback(img => {
    imgRef.current = img;
  }, []);

  const makeClientCrop = async crop => {
    if (imgRef.current && crop.width && crop.height) {
      createCropPreview(imgRef.current, crop, 'newFile.jpeg');
    }
  };
  const makePostCrop = async crop => {
    if (imgRef.current && crop.width && crop.height) {
      createCropPreview(imgRef.current, crop, 'newFile.jpeg');
    }
  };

  const createCropPreview = async (image, crop, fileName) => {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

    ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob(blob => {
        if (!blob) {
          reject(new Error('Canvas is empty'));
          return;
        }
        blob.name = fileName;
        window.URL.revokeObjectURL(previewUrl);
        setPreviewUrl(window.URL.createObjectURL(blob));
      }, 'image/jpeg');
    });
 };

  const onSubmit = (e) => {
    e.preventDefault();
    const config = { responseType: 'blob' };
    let file = axios.get(previewUrl, config).then(response => {
        new File([response.data], title, {type:"image/jpg", lastModified:new Date()});       
    }); 
    let formData = new FormData();
    formData.append('title', title);
    formData.append('headline', headline);
    formData.append('ad_text', ad_text);
    formData.append('file', file);
    addFBFeedAd(formData);


  };
  return (

The Form portion:

<form method="post" id='uploadForm'>                  
          <div className="input-field">
            <label for="id_file">Upload Your Image</label>
            <br/>
            {/* {{form.file}} */}
          </div>
          <div>
            <div>
              <input type="file" accept="image/*" onChange={onSelectFile} />
            </div>
            <ReactCrop
              src={upImg}
              onImageLoaded={onLoad}
              crop={crop}
              onChange={c => setCrop(c)}
              onComplete={makeClientCrop}
              ref={cropper}
            />
            {previewUrl && <img alt="Crop preview" src={previewUrl} />}
          </div>

            <button className="btn darken-2 white-text btn-large teal btn-extend" id='savePhoto' onClick={onSubmit} value="Save Ad">Save Ad</button>

        </form>

Here is the Axios Call:

 export const addFBFeedAd = (fbFeedAd) => (dispatch, getState) => {
  setLoading();
  axios
    .post(`http://localhost:8000/api/fb-feed-ads/`, fbFeedAd, tokenMultiPartConfig(getState))
    .then((res) => {
      dispatch(createMessage({ addFBFeedAd: 'Ad Added' }));
      dispatch({
        type: SAVE_AD,
        payload: res,
      });
    })
    .catch((err) => dispatch(returnErrors(err)));
}

Here Is where I set the headers to multipart form data

export const tokenMultiPartConfig = (getState) => {
 // Get token from state
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      "Content-type": "multipart/form-data",
    },
  };

  // If token, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`;
  }

  return config;
};

The Model:

class FB_Feed_Ad(models.Model):
    title = models.CharField(max_length=100, blank=True)
    headline = models.CharField(max_length=25, blank=True)
    ad_text = models.CharField(max_length=125, blank=True)
    file = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)

The crop preview blob:

blob:http://localhost:3000/27bb58e5-4d90-481d-86ab-7baa717cc023

I console.log-ed the Cropped Image after the axios call.

File:  
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined
AdCreator.js:169 formData: 
FormData {}
__proto__: FormData

As you can see I am trying to submit the blob image file generated by the react-image-cropper, as part of the form data when the form is submitted. I want to save the cropped image to the Django Rest API.
Any suggestions?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM