Blog

How to Download Files From Backendless File Hosting

by on

We’ve written about how to upload files to the Backendless Hosting system. Once a file is uploaded, it gets a public URL which can either be obtained using Backendless Console or calculated using a template.

The template used can be seen here:

https://api.backendless.com/<application id>/<version name>/files/<path>/<file name>

Alternatively, when a file is uploaded, the API call returns the URL of the uploaded file. The sample code below demonstrates how to download the file. The code prints out the contents of the file to the system console, but it can be easily modified to store it in the local file system, or transfer elsewhere over the network, etc.

    public static void downloadFile(BackendlessFile backendlessFile) throws IOException {
       URL url = new URL(backendlessFile.getFileURL());
       HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
       int responseCode = httpConn.getResponseCode();
    
       // always check HTTP response code first
       if (responseCode == HttpURLConnection.HTTP_OK) {
           // opens input stream from the HTTP connection
           InputStream inputStream = httpConn.getInputStream();
    
           InputStreamReader inputStreamReader = new InputStreamReader((inputStream));
           BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    
           Log.i(TAG, "File content is:\n===========================");
    
           String line;
           while ((line = bufferedReader.readLine()) != null) {
               Log.i(TAG, line);
           }
    
           Log.i(TAG, "===========================");
    
           inputStream.close();
           bufferedReader.close();
           inputStreamReader.close();
    
           Log.i(TAG, "File downloaded");
       } else {
           Log.i(TAG, "No file to download. Server replied HTTP code: " + responseCode);
       }
       httpConn.disconnect();
    }

    @Throws(IOException::class)
    fun downloadFile(backendlessFile: BackendlessFile) {
       val url = URL(backendlessFile.fileURL)
       val httpConn = url.openConnection() as HttpURLConnection
       val responseCode = httpConn.responseCode
    
       // always check HTTP response code first
       if (responseCode == HttpURLConnection.HTTP_OK) {
           // opens input stream from the HTTP connection
           val inputStream = httpConn.inputStream
    
           Log.i(TAG, "File content is:\n===========================")
    
           inputStream.reader().forEachLine {
               Log.i(TAG, it)
           }
    
           Log.i(TAG, "===========================")
    
           inputStream.close()
    
           Log.i(TAG, "File downloaded")
       } else {
           Log.i(TAG, "No file to download. Server replied HTTP code: $responseCode")
       }
       httpConn.disconnect()
    }

    NSString *fileUrl = @"https://someurl.com";
    NSURL *url = [NSURL URLWithString:fileUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
    NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data && response) {
            NSLog(@"File has been downloaded");
        }
        else if (error) {
            NSLog(@"Error: %@", [error localizedDescription]);
        }
    }];
    [dataTask resume];

    let fileUrl = "https://someurl.com"     
    if let url = URL(string: fileUrl) {
        let request = URLRequest(url: url)
        let urlSession = URLSession(configuration: .default)
        let dataTask = urlSession.dataTask(with: request) { data, response, error in
            if data != nil, response != nil {
                print("File has been downloaded")
            }
            else if let error = error {
                print("Error: \(error.localizedDescription)")
            }
        }
        dataTask.resume()
    }

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const fileURL = 'https://example.com/path/to/file.txt'
    
    const onSuccess = fileContent => {
      console.log('File content is:\n===========================')
      console.log(fileContent)
      console.log('===========================')
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    Backendless.Request.get(fileURL)
      .then(onSuccess)
      .catch(onError)
    

    static void downloadFile(String url) {
       new HttpClient().getUrl(Uri.parse(url))
       .then((HttpClientRequest request) => request.close())
       .then((HttpClientResponse response) =>
         response.transform(utf8.decoder).listen((contents) {
           print("File content is:\n===========================");
           print(contents);
           print("===========================");
         }));
     }

    4 Comments

    I have created a file named fruits.txt in a folder named gkFiles

    Can someone tell me what value I should specify in this statement …

    const fileURL = ‘https://example.com/path/to/file.txt’

    Hi Gaev, have you looked into the documentation? It talks about how the file URL should be formated:
    https://backendless.com/docs/js/files_file_download.html

    Thank you for the prompt response.

    The link you provided shows the format for (say) accessing the file contents from my browser’s address box (which I had already done) … what threw me off was the example.com/path/to/file.txt

    Since I am asking about accessing the same data via javascript inside my html file, do I still use the REST API key or the JS API key in the url ?

    Thank you.

    Gaev

    You are welcome. You can use any API key, the JS one would make more sense since you get the following benefits:
    – You can see the JavaScript version of your app activity in analytics
    – You can apply security to the JavaScriptUser security role which is associated with the JS API Key

    Leave a Reply