reactjs – 如何使用react保存从服务器下载的文件?

前端之家收集整理的这篇文章主要介绍了reactjs – 如何使用react保存从服务器下载的文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个后端API,它可以在我们调用时基本上下载模板.
我在我的html页面上提供了一个href,因此每当有人点击该href时,它会调用后端API并且该文件应该被下载.

但该文件未下载.

我正在使用React.如果我只是从我的浏览器点击后端,文件会被下载,但如果我从反应中调用它,则不会.

任何线索?

REACT CODE:

const config = require('config');
var aws4 = require('aws4');
const Promise = require('axios');

const requestHelper = {
  appendHeaders(request){
    request.headers = request.headers || {};
    if(request.headers["Content-Type"]){
      return
    }
    request.headers["Content-Type"] = "application/json";
  },externalApi(request,serverResult){
    if(!request.method){
      request.method='POST';
    }
    request.path = request.url
    this.appendHeaders(request)
   console.log('request',request)
    return Promise(request)
    .then((apiResponse) => {
      if (apiResponse.data.errors) {
        var error = apiResponse.data.errors;
        console.log('api error response: ',error);
        serverResult.status(400).json({ error })
      } else {
        console.log('api response: ',apiResponse.data);
        serverResult.status(200).json(apiResponse.data);
      }
    }).catch((error) => {
      console.log('api error response: ',error);
      serverResult.status(400).json({ error });
    });
   },getDownloadResponse(request,serverResult){
    debugger;
    request.path = request.url
    this.appendHeaders(request)
    console.log(request);
    return Promise(request)
    .then((apiResponse) => {
      if (apiResponse.data.errors) {
        var error = apiResponse.data.errors;
        console.log('api error response: ',error);
        serverResult.status(400).json({ error })
      } else {
        serverResult.status(200);
        console.log('api response status: '+200);
      }
    }).catch((error) => {
      console.log('api error response: ',error);
      serverResult.status(400).json({ error });
    });
   }
};

module.exports = requestHelper;

BACKEND API代码

@RequestMapping(value = GlobalConstants.DOWNLOAD_FILE,method = RequestMethod.GET)
public void downloadTemplate(HttpServletRequest hRequest,HttpServletResponse response) throws Exception {

    InputStream in = null;
    OutputStream out = null;
    try {
        if (!StringUtils.isEmpty(sampleFile)) {
            File file = new File(sampleFile);
            in = finderService.downloadFile(sampleFile);
            if (in != null) {
                MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
                response.setContentType(mimetypesFileTypeMap.getContentType(file));
                String headerKey = "Content-Disposition";
                String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
                response.setHeader(headerKey,headerValue);

                out = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer,length);
                }
            }
        } else {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        logger.error("Internal Server error"); //Add logs for server error here also

    } catch (Throwable th) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        logger.error(th);
        return;
    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.flush();
        }
    }
}
JS中的GET请求与访问浏览器中的URL不同.您需要通过指定URL直接在客户端上调用下载,例如:
download() {
  // fake server request,getting the file url as response
  setTimeout(() => {
    const response = {
      file: 'http://releases.ubuntu.com/12.04.5/ubuntu-12.04.5-alternate-amd64.iso',};
    // server sent the url to the file!
    // now,let's download:
    window.open(response.file);
    // you could also do:
    // window.location.href = response.file;
  },100);
}

这是a working example on JSBin.

请注意,如果要下载浏览器可以显示文件(例如JSON,图像,视频),它们将显示在新选项卡中.如果您希望直接下载这些类型的文件,则需要使用一些解决方法,例如使用blob.这里有a few examples of this.

猜你在找的React相关文章