fetch上传formdata图片

要使用Fetch API来上传FormData中的图像数据,可以按照以下步骤进行操作。

  1. 创建一个新的FormData对象并将其赋值为空。
    const formData = new FormData();
  2. 通过append()方法向FormData添加文件字段及相应的图像文件。
// 假设有一个input元素
const imageFile = document.getElementById('imageInput').files[0]; // 获取选定的图像文件
formData.append('image', imageFile); // 'image'是表单字段名称,根据需求自行修改
  1. 构造一个包含URL、HTTP方法(POST)和headers等信息的配置对象。

 

const config = {
    method: 'POST',
    body: formData
};
  1. 发送Fetch请求到服务器。
fetch('/upload-url', config)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.error(error));

在这里,'/upload-url'是指向处理上传图像的后台API的URL地址。根据实际情况进行调整。

你可能感兴趣的:(开发DEMO,Javascript,前端)