简体   繁体   English

从快递路线下载图片

[英]Download image from express route

I have an express server running with the following route: 我有一个运行以下路线的快递服务器:

exports.getUserFile = function (req, resp) {
      let filePath = path.join(__dirname, 'storage', req.params.fileName);
      resp.download(filePath);
  });
}

In my web app i'm calling this route and trying to save the file locally using file-saver : 在我的网络应用中,我正在调用此路由,并尝试使用file-saver在本地保存文件:

let req = request.get('/users/' + userId + '/files/' + file.name);
req.set('Authorization', 'Bearer ' + this.state.jsonWebToken);
req.end((err, resp) => {
  let f = new File([resp.text], file.name, {type: resp.type});
  fileSaver.saveAs(f);
});

If the file is plain text then it works ok, but for other file types like images i'm not able to open the file (it's 'corrupt'). 如果该文件是纯文本格式,则可以正常工作,但是对于其他文件类型(如图像),我无法打开该文件(此文件已损坏)。

This is what the response looks like: 响应如下所示:

屏幕截图

Do I need to decode the data in some way first? 我是否需要先以某种方式解码数据? What is the correct way to save the content of the file? 保存文件内容的正确方法是什么?

I haven't used express for a long time ago and I'm typing from mobile, it's seems a encoding issue, so it's seems that you're a sending raw image, you will need to encode it in base64 try something like: 我很久以前没有使用express了,我是从手机输入的,这似乎是编码问题,所以看来您是在发送原始图像,您需要在base64中对其进行编码,请尝试以下操作:

//Here your saved file needs to be encoded to base 64.
var img = new Buffer(data, 'base64');

   res.writeHead(200, {
     'Content-Type': 'image/png',
     'Content-Length': img.length
   });
   res.end(img);

Where data is your saved image, If you can render the image you just add the headers for download or just chain method download. 数据是保存的图像,如果可以渲染图像,则只需添加标题以供下载,或者仅添加链式方法即可。

If you're using superagent to perform the requests, you can explicitly set the response type to "blob" , which would prevent any attempts to decode the response data. 如果您使用superagent执行请求,则可以将响应类型显式设置为"blob" ,这将防止尝试解码响应数据。 The binary data will end up in resp.body : 二进制数据将以resp.body

req.responseType('blob').end((err, resp) => {
  saveAs(resp.body, file.name);
});

If you want to download the image as attachment in the page you can use res 如果要在页面中将图像作为附件下载,可以使用res

exports.getUserFile = function (req, resp) {
  let filePath = path.join(__dirname, 'storage', req.params.fileName);
  var check = fs.readFileSync(__dirname+req.params.fileName);
  resp.attachment(req.params.fileName); // The name of the file to be saved as. Eg Picture.jpg
  res.resp(check)  // Image buffer read from the path.
});
}

Reference: 参考:

http://expressjs.com/en/api.html#res.attachment http://expressjs.com/zh-CN/api.html#res.attachment

http://expressjs.com/en/api.html#res.end http://expressjs.com/en/api.html#res.end

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM