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

时间:2016-11-20 18:20:48

标签: reactjs

我有一个后端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, 0, 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();
        }
    }
}

2 个答案:

答案 0 :(得分:24)

JS中的GET请求与访问浏览器中的网址不同。您需要通过指定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

答案 1 :(得分:7)

你可以使用React' a' hrefdownload道具的元素:

 <a href={getFile.url}
    download={getFile.saveAsFileName}>
</a>