javascript - 如何使用 axios 从 flask 中获取图像

标签 javascript python flask axios multipartform-data

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

@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)
    }
  })

关于javascript - 如何使用 axios 从 flask 中获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56972948/

相关文章:

javascript - Backbone : Singleton views?

javascript - 如何使用 onEnter Hook 和 $transition$ 防止默认操作? (新的用户界面路由器)

javascript - 函数中的 event.target 未给出预期结果

Python-夏娃 : More than one additional lookup

python - 如何设置像素图的最大宽度和高度?

python - 如何重用逻辑来处理 Python 的 tkinter GUI 中的按键和按钮单击?

python - 使用 Flask 和 Swagger 公开 API 文档

javascript - Bootstrap 幻灯片事件在 AJAX 成功中不起作用

python - 重定向回 Flask

python - 可以在特定端口上运行带有 mod_wsgi 的 Flask 应用程序吗?