Android & Spring Boot: File Upload, List, Download, and Delete


Below is a basic example of how to create an Android application that interacts with a Spring Boot backend for file upload, listing, download, and deletion functionalities.


Spring Boot Backend

  1. Setup Spring Boot Application

    • Add dependencies to pom.xml:
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
      </dependencies>
  2. Controller for File Operations

    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.stream.Collectors;
    
    @RestController
    @RequestMapping("/files")
    public class FileController {
        private static final String UPLOAD_DIR = "uploads";
    
        public FileController() {
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) uploadDir.mkdir();
        }
    
        @PostMapping("/upload")
        public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
            try {
                Path filePath = Paths.get(UPLOAD_DIR, file.getOriginalFilename());
                Files.write(filePath, file.getBytes());
                return ResponseEntity.ok("File uploaded successfully");
            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed");
            }
        }
    
        @GetMapping
        public ResponseEntity<?> listFiles() {
            File folder = new File(UPLOAD_DIR);
            String[] files = folder.list();
            if (files != null) {
                return ResponseEntity.ok(files);
            } else {
                return ResponseEntity.ok(new String[]{});
            }
        }
    
        @GetMapping("/{filename}")
        public ResponseEntity<byte[]> downloadFile(@PathVariable String filename) {
            try {
                Path filePath = Paths.get(UPLOAD_DIR, filename);
                byte[] fileBytes = Files.readAllBytes(filePath);
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                        .body(fileBytes);
            } catch (IOException e) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
        }
    
        @DeleteMapping("/{filename}")
        public ResponseEntity<?> deleteFile(@PathVariable String filename) {
            File file = new File(UPLOAD_DIR, filename);
            if (file.exists() && file.delete()) {
                return ResponseEntity.ok("File deleted successfully");
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("File not found");
            }
        }
    }
    
  3. Run Spring Boot Application

    • Use @SpringBootApplication in the main class.
    • Run the application and ensure endpoints like http://localhost:8080/files work.

Android Application

  1. Add Dependencies Add dependencies in build.gradle:

    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
    implementation 'com.google.code.gson:gson:2.10'
  2. HTTP Helper Class

    import okhttp3.*;
    import java.io.File;
    import java.io.IOException;
    
    public class HttpHelper {
        private static final OkHttpClient client = new OkHttpClient();
        private static final String BASE_URL = "http://localhost:8080/files"; // Use your server's IP
    
        public static void uploadFile(File file, Callback callback) {
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(),
                            RequestBody.create(file, MediaType.parse("application/octet-stream")))
                    .build();
            Request request = new Request.Builder()
                    .url(BASE_URL + "/upload")
                    .post(requestBody)
                    .build();
            client.newCall(request).enqueue(callback);
        }
    
        public static void listFiles(Callback callback) {
            Request request = new Request.Builder()
                    .url(BASE_URL)
                    .get()
                    .build();
            client.newCall(request).enqueue(callback);
        }
    
        public static void downloadFile(String filename, Callback callback) {
            Request request = new Request.Builder()
                    .url(BASE_URL + "/" + filename)
                    .get()
                    .build();
            client.newCall(request).enqueue(callback);
        }
    
        public static void deleteFile(String filename, Callback callback) {
            Request request = new Request.Builder()
                    .url(BASE_URL + "/" + filename)
                    .delete()
                    .build();
            client.newCall(request).enqueue(callback);
        }
    }
    
  3. Activity Example

    import android.os.Bundle;
    import android.widget.Toast;
    import androidx.appcompat.app.AppCompatActivity;
    import okhttp3.Call;
    import okhttp3.Callback;
    import okhttp3.Response;
    
    import java.io.File;
    import java.io.IOException;
    
    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Example: Upload a file
            File file = new File(getFilesDir(), "example.txt");
            HttpHelper.uploadFile(file, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "Upload failed", Toast.LENGTH_SHORT).show());
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "Upload success", Toast.LENGTH_SHORT).show());
                }
            });
    
            // Example: List files
            HttpHelper.listFiles(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "Failed to list files", Toast.LENGTH_SHORT).show());
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseData = response.body().string();
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "Files: " + responseData, Toast.LENGTH_LONG).show());
                }
            });
        }
    }
    

Testing

  • Run the Spring Boot server on your computer.
  • Start the Android emulator or connect a device.
  • Replace localhost with your server's IP if testing on a real device.
  • Test each feature (upload, list, download, delete).

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete