如何使用Cloudinary客户端将Blob URL转换为Base64字符串并检索图像URL?

问题描述

我正在使用React-Dropzone npm来使用样式精美的拖放式文件上传器。我陷入了一个事实,即从8.2.0版本开始的React-Dropzone不包含文件的路径,例如仅用图像名称将其缩短。但是,它们确实提供了Blob网址。我不知道如何将Blob-URL转换为Base64字符串,然后将其发送到Cloudinary。

解决方法

我知道了:

几个小时后,一些好人在StackOverflow上发帖,我把它们拼凑在一起了。

package topic;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class TopicController {

    @Autowired
    private TopicService topicService;


    @RequestMapping("/topics")
    public List<Topic> getAllTopics(){
        return topicService.getAllTopics();
    }
    @RequestMapping("/topics/{id}")
    public Topic getTopic(@PathVariable String id){
        return topicService.getTopic(id);
    }
    @RequestMapping(method = RequestMethod.POST,value = "/topics")
    public void addTopic(@RequestBody Topic topic){
        topicService.addTopic(topic);
    }
    @RequestMapping(method = RequestMethod.PUT,value = "/topics/{id}")
    public void updateTopic(@RequestBody Topic topic,@PathVariable String id){
        topicService.updateTopic(topic,id);
    }

    @RequestMapping(method = RequestMethod.DELETE,value = "/topics/{id}")
    public void deleteTopic(@PathVariable String id){
        topicService.deleteTopic(id);
    }
}
,

另一种方式可以是:

const url = 'blob:http://uri';

const blobToBase64 = (url) => {
  return new Promise((resolve,_) => {
    // do a request to the blob uri
    const response = await fetch(url);

    // response has a method called .blob() to get the blob file
    const blob = await response.blob();

    // instantiate a file reader
    const fileReader = new FileReader();

    // read the file
    fileReader.readAsDataURL(fileReader);

    fileReader.onloadend = function(){
      resolve(fileReader.result); // Here is the base64 string
    }
  });
};

// now you can get the 
blobToBase64(url)
  .then(base64String => {
    console.log(base64String) // i.e: data:image/jpeg;base64,/9j/4AAQSkZJ..
  });

// or with await/async
const file = await blobToBase64(url);
console.log(file) // i.e: data:image/jpeg;base64,/9j/4AAQSkZJ..

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...