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

时间:2019-07-10 14:30:02

标签: javascript python flask axios multipartform-data

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

@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

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

使用Axios的经验不足,但是有些Google搜索使我想到了ReactJS subreddit中提出的类似问题。似乎您需要使用Blob初始化response.data,然后将其传递给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)
    }
  })