DriveApi.java 2.43 KB
Newer Older
1 2
package web.multitask.trismegistoservices.api;

3

4
import lombok.AllArgsConstructor;
5 6 7 8 9 10
import org.json.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import web.multitask.trismegistoservices.model.DriveRequest;
11
import web.multitask.trismegistoservices.services.google.DriveService;
12 13
import javax.annotation.Nullable;

14 15 16
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("drive")
17
@AllArgsConstructor
18 19
public class DriveApi {

20 21 22 23
    DriveService driveService;

    @PostMapping(path = "/public/upload", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public ResponseEntity<?> uploadFile(@ModelAttribute DriveRequest request) {
24 25 26 27
        try {
            String folder_id = request.getFolder_id();
            String file_name = request.getFile_name();
            MultipartFile file = request.getFile();
28 29
            String base64 = request.getBase64();
            String id_file_response = driveService.uploadFile(folder_id, file_name, file, base64);
30
            JSONObject response = new JSONObject();
31
            if (id_file_response == null) {
32
                response.put("status", false);
33 34 35
                response.put("message", "No se pudo subir el archivo," +
                        " existe multiples razones por las cuales esto puede ocurrir," +
                        " por favor verifique que el archivo no sea muy grande o que el formato sea correcto");
36 37 38 39
                return ResponseEntity.badRequest().body(response.toMap());
            } else {
                response.put("status", true);
                response.put("message", "Archivo subido correctamente");
40 41 42
                response.put("file_id", id_file_response);
                response.put("file_url", "https://drive.google.com/file/d/" + id_file_response + "/view?usp=sharing");
                response.put("download_url", "https://drive.google.com/uc?export=download&id="+id_file_response);
43 44 45 46
                return ResponseEntity.ok(response.toMap());
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(e.getMessage());
47 48 49 50 51
        }
    }

    @GetMapping(path = "/public/download/{id}")
    public ResponseEntity<?>  downloadFile(@PathVariable String id, @Nullable @RequestParam(name = "base64") Boolean base64) {
52
        return driveService.getFile(id, !(base64 == null));
53 54
    }

55 56

}