首页 > 解决方案 > Spring Boot - 在远程机器上上传文件

问题描述

我想在远程服务器上上传文件,目前我只能在本地机器上上传。下面是我的代码

@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

提前致谢!

标签: springspring-boot

解决方案


编辑:

1.用例:您想在本地上传文件(即您的应用程序正在运行的地方):

您创建StorageService接口和实现类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);
        }
    }

控制器类:

@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:/";
    }

您可以在https://github.com/spring-guides/gs-uploading-files下找到整个示例。

2.用例:您想将文件上传到远程服务器:

在这种情况下,我建议使用 SFTP。

您创建一个RemoteFileSystemStorageService实现 StorageService(已在第一个用例中创建)。

@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();

        }
    }

推荐阅读