Download File Userwise

Name : Hitarth Singh Rajput
Roll No. : LCS2023040


Assignment :

Consider the existing code and write an API to download a file with their userId.


Implementing the Functionality to fetch files with userId :

The following code is used to get / fetch files from a SQL server using a userId :

    @GetMapping("/user/{userId}")
    ResponseEntity<?> downloadByUserId(@PathVariable("userId") int userId) {
        apiReturnModel = new APIReturnModel();
        fileVec = new Vector<>();
        byte[] file = new byte[100000000];
        String fileType = "image/jpeg";
        try {
            FileModel fileModel = this.fileService.downloadByUserId(userId);
            file = FileUtils.decompressFile(fileModel.getFileData());
            fileType = fileModel.getFileType();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.valueOf(fileType)).body(file);
    }

Subsidiary Code that was added :

FileService.java :

    FileModel downloadByUserId(int userId);

FileRepo.java :

    FileModel findByUserUserId(int userId);

FileServiceImpl.java :

    @Override
    public FileModel downloadByUserId(int userId) {
        return this.fileRepo.findByUserUserId(userId);
    }

Using ARC :

Files Stored in MySQL Database :
Pasted image 20240331013636.png

Pasted image 20240331013814.png

  • On hitting the http://localhost:8085/fileresource/user/3 URL an image is returned, here userId is 3

Full Code (can be ignored) :

(Added a feature to delete a file from the database as well)

FileController.java

// @RequestParam annotation is used to bind the parameter values from the request to the method parameters in the controller
// @PathVariable annotation is used to extract the values from the URI path
// @RequestBody annotation is used to bind the HTTP request/response body with a domain object in method parameter or return type
package com.tool.erp.file.controller;

import java.io.IOException;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.tool.erp.file.model.FileModel;
import com.tool.erp.file.services.FileService;
import com.tool.erp.file.utils.FileUtils;
import com.tool.erp.setup.APIReturnModel;
import com.tool.erp.users.model.UsersModel;
import com.tool.erp.users.service.UserService;

@RestController
@RequestMapping("/fileresource")
public class FileController {

    @Autowired
    private FileService fileService;

    @Autowired
    private UserService userService;

    private APIReturnModel apiReturnModel;
    private Vector<FileModel> fileVec;

    @PostMapping("/")
    ResponseEntity<?> upload(@RequestParam("file") MultipartFile file, @RequestParam("userId") int userId) throws IOException {

        apiReturnModel = new APIReturnModel();
        fileVec = new Vector<>();
        FileModel fileModel = new FileModel();
        fileModel.setFileName(file.getOriginalFilename());
        fileModel.setFileData(FileUtils.compressFile(file.getBytes()));
        fileModel.setFileType(file.getContentType());
        UsersModel user = this.userService.getUserById(userId);
        fileModel.setUser(user);

        try {
            FileModel fileModel2 = this.fileService.uploadFile(fileModel);
            fileVec.add(fileModel2);
            apiReturnModel.setData(fileVec);
            apiReturnModel.setCount(fileVec.size());
            apiReturnModel.setMessage("File Uploaded Successfully !");
            apiReturnModel.setStatus("Success");

        } catch (Exception e) {
            apiReturnModel.setMessage("Something Went Wrong !!");
            apiReturnModel.setStatus("fail");

        }
        return ResponseEntity.ok(apiReturnModel);
    }

    @GetMapping("/{fileId}")
    ResponseEntity<?> download(@PathVariable("fileId") int fileId) {
        apiReturnModel = new APIReturnModel();
        fileVec = new Vector<>();
        byte[] file = new byte[100000000];
        String fileType = "image/jpeg";
        try {
            FileModel fileModel = this.fileService.downloadFile(fileId);
            file = FileUtils.decompressFile(fileModel.getFileData());
            fileType = fileModel.getFileType();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.valueOf(fileType)).body(file);
    }

    @GetMapping("/user/{userId}")
    ResponseEntity<?> downloadByUserId(@PathVariable("userId") int userId) {
        apiReturnModel = new APIReturnModel();
        fileVec = new Vector<>();
        byte[] file = new byte[100000000];
        String fileType = "image/jpeg";
        try {
            FileModel fileModel = this.fileService.downloadByUserId(userId);
            file = FileUtils.decompressFile(fileModel.getFileData());
            fileType = fileModel.getFileType();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.valueOf(fileType)).body(file);
    }

    @DeleteMapping("/{userId}")
//    @RequestMapping(value="/user/{userId}", method=RequestMethod.DELETE)
    public ResponseEntity<?> deleteFilesByUserId(@PathVariable("userId") int userId) {
        apiReturnModel = new APIReturnModel();
        try {
            this.fileService.deleteFile(userId);
            apiReturnModel.setMessage("Files deleted successfully.");
            return ResponseEntity.status(HttpStatus.OK).body(apiReturnModel);
        } catch (Exception e) {
            e.printStackTrace();
            apiReturnModel.setMessage("Failed to delete files.");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(apiReturnModel);
        }
    }
}

FileService.java

package com.tool.erp.file.services;

import com.tool.erp.file.model.FileModel;
import org.springframework.transaction.annotation.Transactional;

public interface FileService {

    FileModel uploadFile(FileModel fileModel);

    FileModel downloadFile(int fileId);

    FileModel downloadByUserId(int userId);

    @Transactional
    void deleteFile(int fileId);
}

FileServiceImpl.java

package com.tool.erp.file.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tool.erp.file.model.FileModel;
import com.tool.erp.file.repositories.FileRepo;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileRepo fileRepo;

    @Override
    public FileModel uploadFile(FileModel fileModel) {
        return this.fileRepo.save(fileModel);
    }

    @Override
    public FileModel downloadFile(int fileId) {
        return this.fileRepo.findByFileId(fileId);
    }

    @Override
    public FileModel downloadByUserId(int userId) {
        return this.fileRepo.findByUserUserId(userId);
    }

    public void deleteFile(int userId) {
        fileRepo.deleteByFileId(userId);
    }
}

FileRepo.java

package com.tool.erp.file.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import com.tool.erp.file.model.FileModel;

public interface FileRepo extends JpaRepository<FileModel, Integer> {
    FileModel findByFileId(int fileId);
    FileModel findByUserUserId(int userId);
    void deleteByFileId(int fileId);
}