Search code examples
javareactjsspringspring-bootinputstream

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


The code below uses a protected url ,username password to get the files to download. I can only manage to download the file in the springboot folder. I want to send the file data to the frontend to have it download there to your downloads.

I might be wrong but I need to send the inputstream to the frontend, then download that data to a file? Any suggestions as to what I am doing wrong when trying to send this data to the frontend.

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

Solution

  • //Complete redo of the code

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

    FRONTEND

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