【问题标题】: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我想从前端下载一个文件,需要将输入流发送到前端。使用下载链接从后端下载文件
【发布时间】:2022-01-06 04:01:24
【问题描述】:

下面的代码使用受保护的 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);
    
        }

【问题讨论】:

    标签: java reactjs spring spring-boot inputstream


    【解决方案1】:

    //完全重做代码

    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);
          }
        );
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2021-08-31
      • 2020-07-18
      • 2019-03-10
      • 2021-10-02
      • 2021-06-27
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      相关资源
      最近更新 更多