chengaofeng
发布于 2024-07-01 / 11 阅读
0
0

上传文件使用表单数据提交时,有特殊字符导致报错

上传文件使用表单数据提交时,有特殊字符导致报错时,可以将数据用json字符串传递

        const start = item[i].chunk * chunkSize
        const end = Math.min(file.size, start + chunkSize)
        const chunk = file.slice(start, end)
        const chunkMd5 = await getFileMd5(chunk)
        const data = new FormData()
        data.append('file', chunk)
// 除上传的文件外,其它描述信息用json字符串传递
        data.append(
          'uploadJO',
          JSON.stringify({
            fileName: file.name,
            fileMd5,
            chunk: item[i].chunk,
            chunkMd5,
            envId: info.envId,
            uuid: info.uuid
          })
        )
        // data.append('fileName', file.name)
        // data.append('fileMd5', fileMd5)
        // data.append('chunk', item[i].chunk)
        // data.append('chunkMd5', chunkMd5)
        // data.append('envId', info.envId)
        // data.append('uuid', info.uuid)

在进行表单上传时,如果你想要同时传输文件和一些额外的数据(以JSON格式),你可以使用FormData对象来构建你的请求体。FormData允许你以一种键值对的形式来组织数据,其中既可以包含文件也可以包含文本字段。然后,你可以将这个FormData对象作为请求体发送。

function uploadFileWithJsonData(file, jsonData) {
  // 创建一个FormData对象
  const formData = new FormData();

  // 添加文件到表单数据中
  formData.append('file', file);

  // 将额外的JSON数据转换为字符串并添加到表单数据中
  // 假设jsonData是一个对象,例如:{ key1: 'value1', key2: 'value2' }
  formData.append('jsonData', JSON.stringify(jsonData));

  // 使用fetch或者其他HTTP客户端库来发送请求
  fetch(`${BASE_URL}/uploadbigfile/uploadWithJson`, {
    method: 'POST',
    body: formData,
    // 注意:当使用FormData时,不要手动设置Content-Type头部,浏览器会自动设置
  })
  .then(response => response.json())
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.error('Error:', error);
  });
}

// 使用示例
const file = document.querySelector('input[type="file"]').files[0];
const jsonData = { key1: 'value1', key2: 'value2' };
uploadFileWithJsonData(file, jsonData);

在这个示例中,首先创建了一个FormData对象,并使用append方法添加了文件和JSON数据。对于JSON数据,要先将其转换为字符串,因为FormData只能处理文本值或者二进制内容。然后,我们使用fetch函数发送了一个包含这个FormData对象的POST请求。

请注意,当使用FormData时,不应该手动设置Content-Type请求头。浏览器会自动为你的请求设置正确的Content-Type,包括正确的boundary参数。


评论