wumingstyle 2015-06-02 08:47 采纳率: 0%
浏览 1276

SAE中用php上传文件到FTP服务器

现在SAE里边支持php的 @ftp_connect($FTP_HOST,$FTP_PORT) 方法吗?查资料说是不支持,所以用了curl模拟ftp上传,在上传的时候 curl_setopt($ch, CURLOPT_URL, 'ftp://username:password@IP:21/'.$dir.'/'.$dest); 这个URL应该怎么写呢?这个目录是指要传到的FTP服务器的目录吗?运行的时候会报 AE ERROR: INVALID URI 这个错误。图片说明我先想把SAESTOR里边的一个文件传到ftp服务器 home/wuming 目录下边 取名aaa.txt。这样写有什么问题吗?刚接触这块,大神勿喷……

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-03 22:55
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在使用SAE(Spring Boot框架)时,您不能直接使用@ftp_connect方法来连接FTP服务器。然而,您可以创建一个自定义的类,并重写execute()方法以实现您的需求。

    以下是一个简单的示例:

    import org.springframework.core.io.FileSystemResource;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.web.multipart.MultipartFile;
    
    public class CustomFtpClient {
    
        public static void main(String[] args) {
            String ftpHost = "example.com";
            int ftpPort = 21;
            String username = "username";
            String password = "password";
    
            try {
                CustomFtpClient client = new CustomFtpClient();
                client.upload("home/wuming", "/aas.txt", "aaa.txt");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private void upload(String dir, String src, String dest) throws Exception {
            // Create an FTP connection and use it to upload the file
            // Note that this is just a simple example and does not handle authentication or error handling.
            File ftpDir = new File(dir);
            if (!ftpDir.exists()) {
                ftpDir.mkdirs();
            }
            FTPClient ftp = new FTPClient();
            ftp.connect(ftpHost, ftpPort);
            ftp.login(username, password);
            ftp.changeWorkingDirectory(dir);
    
            // Upload the file
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, bytesRead);
            }
            in.close();
            out.close();
    
            // Ensure the directory exists before uploading
            ftp.changeWorkingDirectory("/");
            ftp.mkd("/" + dest.substring(0, dest.lastIndexOf('/')));
        }
    
    }
    

    在这个示例中,我们首先创建了一个FTP客户端对象,然后调用upload方法来上传文件。注意,这是一个非常基本的例子,实际使用时可能需要处理更多的情况,例如验证用户身份、处理错误等。

    此外,请确保您的FTP服务器允许通过匿名登录访问,否则您将无法上传文件。

    评论

报告相同问题?