我想从前端下载一个文件,需要将输入流发送到前端。使用 download link 从后端下载文件

I want to download a file from the frontend, need to send input stream to the frontend. Using download link to download file from backend

下面的代码使用受保护的 url 用户名密码来获取要下载的文件。我只能设法下载springboot文件夹中的文件。我想将文件数据发送到前端,以便将其下载到您的下载中。

我可能错了,但我需要将输入流发送到前端,然后将该数据下载到文件中?关于我在尝试将此数据发送到前端时做错了什么的任何建议。

@RequestMapping(value = "/checkIfProtectedOrPublic/", method = RequestMethod.POST)
        public ResponseEntity checkIfProtectedOrPublic(@RequestPart("prm_main") @Valid CheckProtectedData checkProtectedData) throws IOException {
    
            List<PrmMain> prmMainList = prmMainRepository.findAllByCode("PROTECTED_LOGIN");
            boolean success = true;
            InputStream in = null;
            FileOutputStream out = null;
    
    
            for (int i = 0; i < prmMainList.size(); i++) {
                if (prmMainList.get(i).getData().get("email").equals(checkProtectedData.getEmail())) {
    
    String username= (String) prmMainList.get(i).getData().get("email");
    String password= (String) prmMainList.get(i).getData().get("password");
    
    
    
                    try{
                        URL myUrl = new URL(checkProtectedData.getDownloadLink());
                        HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
                        conn.setDoOutput(true);
                        conn.setReadTimeout(30000);
                        conn.setConnectTimeout(30000);
                        conn.setUseCaches(false);
                        conn.setAllowUserInteraction(false);
                        conn.setRequestProperty("Content-Type", "application/json");
                        conn.setRequestProperty("Accept-Charset", "UTF-8");
                        conn.setRequestMethod("GET");
    
                        String userCredentials = username.trim() + ":" + password.trim();
                        String basicAuth = "Basic " + new String(Base64.encode(userCredentials.getBytes()));
                        conn.setRequestProperty ("Authorization", basicAuth);
    
                        in = conn.getInputStream();
    
    
                        out = new FileOutputStream(checkProtectedData.getFileName());
                        int c;
                        byte[] b = new byte[1024];
    
                        while ((c = in.read(b)) != -1){
                            out.write(b, 0, c);
                        }
                    }
    
                    catch (Exception ex) {
    
                        success = false;
                    }
    
                    finally {
                        if (in != null)
                            try {
                                in.close();
                            } catch (IOException e) {
    
                            }
                        if (out != null)
                            try {
                                out.close();
                            } catch (IOException e) {
    
                            }
                    }
                }
            }
    
    
    
            return ResponseEntity.of(null);
    
        }

//代码重做

PrmMain loginParameter = prmMainRepository.findAllByCode("PROTECTED_LOGIN").get(0);

        if (loginParameter == null)
            throw new IllegalArgumentException("Protected Login Not Configured");

        // now try and download the file to a byte array using commons - this bypasses CORS requirements
        HttpGet request = new HttpGet(checkProtectedData.getDownloadLink());
        String login = String.valueOf(loginParameter.getData().get("email"));
        String password = String.valueOf(loginParameter.getData().get("password"));
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(login, password));
        try
                (
                        CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
                        CloseableHttpResponse response = httpClient.execute(request)
                )
        {
            // if there was a failure send it
            if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value())
                return new ResponseEntity<>(HttpStatus.valueOf(response.getStatusLine().getStatusCode()));

            // send back the contents
            HttpEntity entity = response.getEntity();
            if (entity != null)
            {
                // return it as a String
                HttpHeaders header = new HttpHeaders();
                header.setContentType(MediaType.parseMediaType(entity.getContentType().getValue()));
                header.setContentLength(entity.getContentLength());
                header.set("Content-Disposition", "attachment; filename=" + checkProtectedData.getFileName());
                return new ResponseEntity<>(EntityUtils.toByteArray(entity), header, HttpStatus.OK);
            }
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

前端

export async function DownloadFile(url, request) {
    axios({
        url: `${localUrl + url}`, //your url
        method: 'POST',
        data: request,
        responseType: 'blob', // important
    }).then((response) => 
    {
        fileSaver.saveAs(new Blob([response.data]), request.fileName);
        return true;
    }).catch(function (error)
      {
        console.error('Failed ', error);
        console.error('Failed ', error); console.log('Failed ', error);
      }
    );
}