Загрузка файла SFTP при весенней загрузке - PullRequest
0 голосов
/ 22 апреля 2020

Я создал одно весеннее загрузочное приложение. Мне нужно загрузить любой файл (do c, pdf, mp3 et c ..) на сервер sftp. когда пользователь загружает файл, мое весеннее приложение может создавать URL-адреса и сохранять сведения о файле (на котором расположен файл сервера, загружать URL-адрес файла, который является владельцем этого файла и т. д. c ..) в базу данных h2. и когда пользователь запрашивает файл .. весенний загрузчик может получить информацию о файле из базы данных .. и отобразить этот файл в браузере. и пользователь также может загрузить этот файл. может любой помочь .. введите описание изображения здесь

Java Конфигурация

import com.example.springintegrationhttp.FilePrinter;
import org.springframework.context.annotation.Bean;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.filters.AcceptOnceFileListFilter;
import org.springframework.integration.sftp.filters.SftpSimplePatternFileListFilter;
import org.springframework.integration.sftp.inbound.SftpInboundFileSynchronizer;
import org.springframework.integration.sftp.inbound.SftpInboundFileSynchronizingMessageSource;
import org.springframework.integration.sftp.outbound.SftpMessageHandler;
import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

import java.io.File;

@org.springframework.context.annotation.Configuration
@Component
public class Configuration {

    @Bean
    public DefaultSftpSessionFactory sftpSessionFactory(){
        DefaultSftpSessionFactory defaultSftpSessionFactory = new DefaultSftpSessionFactory();
        defaultSftpSessionFactory.setHost("0.0.0.0");
        defaultSftpSessionFactory.setPort(22);
        defaultSftpSessionFactory.setUser("abhishek");
        defaultSftpSessionFactory.setPassword("12345");
        defaultSftpSessionFactory.setAllowUnknownKeys(true);
        System.out.println("Value in SftpSession: " + defaultSftpSessionFactory);
        return defaultSftpSessionFactory;
    }
        @Bean
        @ServiceActivator(inputChannel = "tosftpChannel")
        public MessageHandler handler(){
            SftpMessageHandler messageHandler = new SftpMessageHandler(sftpSessionFactory());
            messageHandler.setRemoteDirectoryExpression(new LiteralExpression("upload"));
            messageHandler.setFileNameGenerator(new FileNameGenerator() {
                @Override
                public String generateFileName(Message<?> message) {
                    System.out.println(message.getHeaders().get("fileName"));
                    System.out.println(message.getPayload());
                    return message.getHeaders().get("fileName").toString();
                }
            });
            return messageHandler;
        }

    @Bean
    public SftpInboundFileSynchronizer sftpInboundFileSynchronizer(){
        SftpInboundFileSynchronizer fileSynchronizer = new SftpInboundFileSynchronizer(sftpSessionFactory());
        fileSynchronizer.setDeleteRemoteFiles(false);
        fileSynchronizer.setRemoteDirectory("upload");
        System.out.println("M a gaya");
        fileSynchronizer.setFilter(new SftpSimplePatternFileListFilter("*.txt"));
        return fileSynchronizer;
    }
    @Bean
    //@InboundChannelAdapter(channel = "sftpChannel", poller = @Poller(fixedDelay = "5000"))//,autoStartup = "false")
    @InboundChannelAdapter(channel = "sftpChannel")//,autoStartup = "false")
    public MessageSource<File> sftpMessageSource(){
        System.out.println("Into sftpMessageSource()");
        SftpInboundFileSynchronizingMessageSource source = new SftpInboundFileSynchronizingMessageSource(sftpInboundFileSynchronizer());
        source.setLocalDirectory(new File("target/foo"));
        source.setAutoCreateLocalDirectory(true);
        System.out.println("Flow");
        source.setLocalFilter(new AcceptOnceFileListFilter<File>());
        source.setMaxFetchSize(1);
        //sftpInboundFileSynchronizer();
        return source;
    }

    /*OutBoundGateway*/
      /*  @Bean
        @ServiceActivator(inputChannel = "sftpChannel",)
        public MessageHandler handler(){
            SftpOutboundGateway outboundGateway = new SftpOutboundGateway(sftpSessionFactory(),
                    "get","payload");
            outboundGateway.setLocalDirectory(new File("target/gatewayhand"));
            outboundGateway.setAutoCreateLocalDirectory(true);
            return outboundGateway;
        }*/
    /*OutBoundGateway*/


    @Bean
    @ServiceActivator(inputChannel = "sftpChannel")
    public MessageHandler DownloadHandler(){
        //return new SftpOutboundGateway(sftpSessionFactory(),"ls");
       return message -> {
           System.out.println("In Service Activator: " + message.getPayload());

           File f = (File) message.getPayload();
           FilePrinter f2 = new FilePrinter();
           f2.print(f);
           System.out.println(f.getName());
           //sftpMessageSource();
           //p.print(File file);

       };
    }
}

Шлюз

import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;

@Component
@MessagingGateway
public interface UplaodGateway {
    @Gateway(requestChannel = "tosftpChannel")
    public void sendToSftp(@Header("fileName") String fileName, InputStream file);
   /* @Gateway(requestChannel = "sftpChannel")
    public void read(String fileName);*/
}

Контроллер

import com.example.springintegrationhttp.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.websocket.server.PathParam;
import java.io.IOException;

@RestController
//@RequiredArgsConstructor
public class uplaodController {

    @Autowired
    UploadService uploadService;

    @PostMapping("/upload")
    public ResponseEntity<String> upladFile(@RequestParam("file")MultipartFile file) throws IOException {
        return uploadService.uplaodToServer(file);
    }
    @GetMapping("/read")
    public String readf(@PathParam("fileName")String fileName){
      uploadService.readFileFromServer(fileName);
        return "I want to fetch that file which user want";
    }
}

//}

Спасибо

...