通过js fetch将图片发送到服务器

时间:2021-01-23 00:23:52

标签: javascript python django fetch

我正在更改我的表单提交,以通过使用 fetch 使其更加流畅。

为了处理我输入图像的值:

<input name="perfil" type='file' id="imageUpload />

然后,为了将其上传到 Amazon S3,

我在我的 views.py 中这样做:

if request.method == "POST"
    image = request.FILES['perfil']

    im = Image.open(image)

    output = BytesIO()

    rgb_im = im.convert('RGB')
    rgb_im.save(output, format='JPEG', quality=90)
    output.seek(0)
            
    s3.Bucket('bucketname').upload_fileobj(output, request.user.email + '.profileImage')

但是现在(因为我正在尝试实现 fetch),我正在获取这样的图像文件:

fetch(`url`, {
  method: 'POST',
  body: JSON.stringify({
    image: document.querySelector('#imageUpload').files[0],
  }),
  headers: {
    "Content-type": "application/json; charset=UTF-8",
    "X-CSRFToken": getCookie('csrftoken')
  }
})

}

问题是,当我在服务器 (views.py) 中执行 request.body['image`] 时,我得到的只是:"image":{}

而且我在将它发送到服务器之前不知道如何在 JS 中处理这个文件(最终将它上传到亚马逊 s3)

1 个答案:

答案 0 :(得分:0)

通过此示例,您可以在服务器上上传图像!

// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');

// This will upload the file after having read it
const upload = (file) => {
  fetch('http://www.example.net', { // Your POST endpoint
    method: 'POST',
    headers: {
      // Content-Type may need to be completely **omitted**
      // or you may need something
      "Content-Type": "You will perhaps need to define a content-type here"
    },
    body: file // This is your file object
  }).then(
    response => response.json() // if the response is a JSON object
  ).then(
    success => console.log(success) // Handle the success response object
  ).catch(
    error => console.log(error) // Handle the error response object
  );
};

// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);

// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);