问题描述
我正在使用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..