如何使用 axios 从烧瓶中获取图像

How to GET image from flask with axios

那是我的烧瓶测试路线,应该给出图像:

@app.route('/marknext', methods=['GET', 'POST'])
def marknext():
    id = request.form.get("ID")
    if request.method == 'POST':
        return "OK"
    else:
        image_file_path = '/home/cnd/contrib/python/input/ChinaSet_AllFiles/CXR_png/CHNCXR_0370_1.png'
        # res = make_response(send_file(image_file_path, add_etags=False, cache_timeout=0))
        # return res
        return send_file(image_file_path, add_etags=False, cache_timeout=0, attachment_filename='CHNCXR_0370_1.png')

在客户端,我试图用 axios 获取该文件并将其放入 <img>

  axios.get('/marknext', {
    params: {
      ID: 0
    }
  })
  .then(function (response) {
    var reader = new window.FileReader();
    reader.readAsDataURL(response.data); 
    reader.onload = function() {
      var imageDataUrl = reader.result;
      $("#selected-image").attr("src", imageDataUrl)
    }
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });

我在控制台上收到错误消息:

TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
    at mark.js:14

我做错了什么?

使用 Axios 的经验不多,但一些谷歌搜索让我想到了 ReactJS subreddit 中提出的类似问题。似乎您需要使用 response.data 初始化 Blob,然后将其传递给 readAsDataURL() 而不是直接传递给 response

.then(function (response) {
    var responseBlob = new Blob([response.data], {type:"image/png"}); 
    var reader = new window.FileReader();
    reader.readAsDataURL(responseBlob); 
    reader.onload = function() {
      var imageDataUrl = reader.result;
      $("#selected-image").attr("src", imageDataUrl)
    }
  })