HorseFileDao.java 1.93 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
package at.ac.tuwien.sepm.assignment.individual.persistence.impl;

import at.ac.tuwien.sepm.assignment.individual.persistence.FileDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.FileSystemException;
import java.nio.file.Files;

@Repository
public class HorseFileDao implements FileDao {
    @Value("${spring.upload.path}")
    private String FILE_BASE_PATH;
    private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
    public HorseFileDao() {};

    @Override
    public void save(MultipartFile file) throws IOException {
        if(file == null || file.getOriginalFilename() == null || file.isEmpty())
            throw new IOException("Cannot save an empty file");

        if(!file.getContentType().equals("image/jpeg") && !file.getContentType().equals("image/png"))
            throw new IOException("Unsupported file type");

        String fileName = file.getOriginalFilename();
        LOGGER.trace("Writing file to " + FILE_BASE_PATH + fileName);

        try {
            // Create directory if it doesn't exist
            File uploadDir = new File(FILE_BASE_PATH);
            if(!uploadDir.exists())
                uploadDir.mkdir();

            // Save the file
            if(uploadDir.exists()) {
                File target = new File(FILE_BASE_PATH + fileName);
                Files.write(target.toPath(), file.getBytes());
            } else {
                throw new FileSystemException("Base upload directory " + FILE_BASE_PATH + " does not exist");
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            throw new IOException("Saving the file failed");
        }
    }
}