ftp上传下载

	1、添加依赖
	<dependency>
        <groupId>commons-net</groupId>
        <artifactId>commons-net</artifactId>
        <version>3.6</version>
    </dependency>

2、上传
  @ResponseBody
@PostMapping("/image")
@ApiOperation("上传图片当前服务器")
public Result upload1(@RequestParam(value="file") MultipartFile multipartFile) {
    Result result = new Result();
    try {
        //获取原始图片名称
        String oddName = multipartFile.getOriginalFilename();
        //获取原始图片扩展名
        String suffix = oddName.substring(oddName.lastIndexOf("."));
        //重新命名图片
        long time = new Date().getTime();
        String prefix = UUID.randomUUID().toString().replace("-", ""); //设置为随机数
        String newName = "file_" + prefix + "_" + time + suffix;
        // 图片上传
        String filepath = new DateTime().toString("yyyy/MM/dd/HH");
        boolean flag = FtpUtil.uploadFile(host, Integer.parseInt(port), username, password, basePath, filepath , newName, multipartFile.getInputStream());
        if (flag) {
            result.setSuccess(true);
            result.setResult(basePath +"/"+ filepath + "/" + newName);
            return result;
        }else {
            result.setSuccess(false);
            result.setMessage("上传失败.");
            return result;
        }
    } catch (IOException e) {
        e.printStackTrace();
        result.setSuccess(false);
        result.setMessage("上传失败.");
        return result;
    }
}

ftp上传工具类

public class FtpUtil {

/**
 * Description: 向FTP服务器上传文件
 *
 * @param host     FTP服务器hostname
 * @param port     FTP服务器端口 21
 * @param username FTP登录账号
 * @param password FTP登录密码
 * @param basePath FTP服务器基础目录,需要绝对路径 比如:/home/ftpuser/www/images
 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
 * @param filename 上传到FTP服务器上的文件名
 * @param input    输入流
 * @return 成功返回true,否则返回false
 */
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                 String filePath, String filename, InputStream input) throws IOException {
    boolean result = false;
    FTPClient ftp = new FTPClient();
    try {
        int reply;
        ftp.connect(host, port);// 连接FTP服务器
        // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
        ftp.login(username, password);// 登录
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return result;
        }
        //切换到上传目录
        if (!ftp.changeWorkingDirectory(basePath + filePath)) {
            //如果目录不存在创建目录
            String[] dirs = filePath.split("/");
            String tempPath = basePath;
            for (String dir : dirs) {
                if (null == dir || "".equals(dir)) continue;
                tempPath += "/" + dir;
                if (!ftp.changeWorkingDirectory(tempPath)) {
                    if (!ftp.makeDirectory(tempPath)) {
                        return result;
                    } else {
                        ftp.changeWorkingDirectory(tempPath);
                    }
                }
            }
        }
        //设置上传文件的类型为二进制类型
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        //上传文件
        if (!ftp.storeFile(filename, input)) {
            System.out.println("uploadFile return 2...");
            return result;
        }
        input.close();
        ftp.logout();
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
   return result;
}

}

 下载回显  path 未路径+文件名

@ApiOperation("ftp图片回显")
@GetMapping("/downloadPic")
public void downloadPic(@RequestParam("path") String path, HttpServletResponse response) {
    FTPClient ftp = new FTPClient();
    String remotePath = path.substring(0, path.lastIndexOf("/"));
    String fileName = path.substring(path.lastIndexOf("/") + 1);
    try {
        int reply;
        ftp.connect(host, Integer.parseInt(port));
        // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
        ftp.login(username, password);// 登录
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        ftp.enterLocalPassiveMode();
        ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
        InputStream in = ftp.retrieveFileStream(fileName);
        response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.addHeader("charset", "utf-8");
        response.addHeader("Pragma", "no-cache");
        String encodeName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
        ServletOutputStream sos = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            sos.write(buffer, 0, len);
        }
        in.close();
        sos.close();
        ftp.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}

3、下载图片

/**
* Description: 从FTP服务器下载文件【使用ftp客户端下载】
*
* @param remotePath FTP服务器上的相对路径
* @param fileName 要下载的文件名
* @return
*/
@PostMapping("/downloadImage")
@ApiOperation(“ftp下载图片”)
public boolean downloadFile(@RequestParam(“url”) String remotePath,
@RequestParam(“fileName”) String fileName,
HttpServletRequest request) {
String contextPath = request.getContextPath();
String localPath = “D:/web/img/pic”;
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, Integer.valueOf(port));
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
// 设置被动模式,开通一个端口来传输数据
ftp.enterLocalPassiveMode();
// 转移到FTP服务器目录
ftp.changeWorkingDirectory(remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File file = new File(localPath);
if (!file.exists()) {
file.mkdirs();
}
File localFile = new File(localPath + “/” + ff.getName());

                OutputStream is = new FileOutputStream(localFile);
                ftp.retrieveFile(ff.getName(), is);
                is.close();
            }
        }

        ftp.logout();
        result = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return result;
}

上传到项目路径

InputStream inputStream = multipartFile.getInputStream();
String contextPath = this.getClass().getClassLoader().getResource("").getPath();
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
File fs = new File(courseFile+"/image/");
if(!fs.exists()){
fs.mkdirs();
}
File f = new File(courseFile+"/image/"+multipartFile.getOriginalFilename());
multipartFile.transferTo(f);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Qt是一种跨平台的C++开发框架,提供了丰富的功能和类库,使得FTP下载变得简单易用。 首先需要在Qt中引入相关的网络模块,包括QTcpSocket和QFtp。QTcpSocket用于与FTP服务器建立连接和数据输,而QFtp则封装了FTP协议的一些常见操作,如连接、登录、上下载等。 要上文件到FTP服务器,首先需要创建一个QTcpSocket对象,并与服务器建立连接。然后,使用QFtp对象的connectToHost()函数连接到FTP服务器,并使用login()函数进行登录验证。如果登录成功,就可以使用put()函数上指定的文件。 要从FTP服务器下载文件,同样需要先创建一个QTcpSocket对象,并与服务器建立连接。然后,使用QFtp对象的connectToHost()函数连接到FTP服务器,并使用login()函数进行登录验证。如果登录成功,就可以使用get()函数下载指定的文件。 FTP下载过程中,可以使用QFtp对象的各种信号和槽函数来处理事件,如上下载进度、错误处理等。 在Qt中进行FTP下载操作相对简单,只需几行代码即可完成。同时,Qt的网络模块提供了良好的跨平台支持,可以在多个操作系统上运行,使得开发和部署更加方便。 总之,使用Qt进行FTP下载操作非常简单,只需借助QTcpSocket和QFtp等相关类库,即可完成连接、登录、上下载等操作。通过Qt的信号和槽机制,还可以方便地处理事件和错误。对于需要实现FTP功能的应用程序而言,Qt是一个强大且便捷的选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值