DEV Community

橙某人
橙某人

Posted on

Convert an image address into a file stream and upload it again

async function imageToStorage(path) {
  // get file name
  const startIndex = path.lastIndexOf('/');
  const endIndex = path.indexOf('?');
  const imgName = path.substring(startIndex + 1, endIndex);
  // get file object of image object
  const file = await getImgToFile(path, imgName);
  // TODO: 将File对象上传到其他接口中
}

/**
 * @name Request files through fetch and convert them into file stream objects
 * @param { string } path 
 * @param { string } fileName 
 * @returns { File | undefined }
 */
function getImgToFile(path, fileName) {
  const response = await fetch(path);
  if (response) {
    const blob = await response.blob();
    const file = new File([blob], fileName, { type: blob.type });
    return file;
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)