Unicorn
Unicorn

Reputation: 295

Spring Boot - Upload files on Remote Machine

I want to upload file on remote server, currently i am only able to upload on local machine. below is my code

@PostMapping("/upload")
public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
    String fileName = fileStorageService.storeFile(file);

    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/downloadFile/")
            .path(fileName)
            .toUriString();

    return new UploadFileResponse(fileName, fileDownloadUri,file.getContentType(), file.getSize());
}

file.upload-dir=C:\\Test

Thanks in Advance!

Upvotes: 0

Views: 5614

Answers (1)

Katy
Katy

Reputation: 1157

EDIT:

1. Use case : You want to upload the file locally (i.e. where your application is running):

You create StorageService interface and an implementing class FileSystemStorageService:

@Service
public class FileSystemStorageService implements StorageService {

    private final Path rootLocation;

    @Autowired
    public FileSystemStorageService(StorageProperties properties) {
        this.rootLocation = Paths.get(properties.getLocation());
    }

    @Override
    public void store(MultipartFile file) {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file " + filename);
            }
            if (filename.contains("..")) {
                // This is a security check
                throw new StorageException(
                        "Cannot store file with relative path outside current directory "
                                + filename);
            }
            try (InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, this.rootLocation.resolve(filename),
                    StandardCopyOption.REPLACE_EXISTING);
            }
        }
        catch (IOException e) {
            throw new StorageException("Failed to store file " + filename, e);
        }
    }

And the controller class:

@Controller
public class FileUploadController {

    private final StorageService storageService;

    @Autowired
    public FileUploadController(StorageService storageService) {
        this.storageService = storageService;
    }


    @PostMapping("/")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
            RedirectAttributes redirectAttributes) {

        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/";
    }

You can find the whole sample under https://github.com/spring-guides/gs-uploading-files.

2. Use case : You want to upload the file to a remote server:

I recommend in this case to use SFTP.

You create a RemoteFileSystemStorageService implementing the StorageService (Already created in the first use case).

@Service
public class RemoteFileSystemStorageService implements StorageService {

    @Autowired
    private StorageProperties properties

    final private ChannelSftp channelSftp;



     @PostConstruct
     public void setUpSsh(){
     JSch jsch = new JSch();
     Session jschSession = jsch.getSession(properties.getUsername(), 
     properties.getRemoteHost());
     jschSession.setPassword(properties.getPassword());
     jschSession.connect();
     this.channelSftp = (ChannelSftp)jschSession.openChannel("sftp");     
     }


    @Override
    public void store(MultipartFile file) {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        try {
            if (file.isEmpty()) {
                throw new StorageException("Failed to store empty file " + filename);
            }
            if (filename.contains("..")) {
                // This is a security check
                throw new StorageException(
                        "Cannot store file with relative path outside current directory "
                                + filename);
            }
            try (InputStream inputStream = file.getInputStream()) {
              this.channelSftp.connect();
              this.channelSftp.put(inputStream, properties.getRemoteServerDirectory());
            }
        }
        catch (IOException e) {
            throw new StorageException("Failed to store file " + filename, e);
        }
        finally{
            this.channelSftp.close();

        }
    }

Upvotes: 1

Related Questions