Java项目中使用FTP与SFTP上传图片

    前面的文章中我们提到了使用ajax异步上传图片,这里想讲讲后台的代码,因为操作系统的原因,我们要在项目中实现windows环境的SFTP上传,linux环境的FTP上传,因此做了一个判断,相关的类文件如下:

1、首先通过Controller将页面扭转至图片上传页面,然后通过异步的方式实现文件上传,Controller如下:

@Controller
public class ImageUploadController
{
    private static final Logger logger = Logger.getLogger(ImageUploadController.class);

    
    @Autowired
    private ImageUploadService imageUploadService;
    

    @RequestMapping("jump_image_upload.xhtml")
    public ModelAndView jumpUploadImage(@RequestParam(value = "picUrl", required = false)
    String picUrl)
    {
        return new ModelAndView("image_upload").addObject("fileUrl", picUrl);
    }


    @RequestMapping(value = "image_upload.json", method = RequestMethod.POST)
    public void upload(@RequestParam(value="uploadFile")MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException
    {
        Map<String,String> model = new HashMap<String, String>();
        String fileName = this.generateFileName(file.getOriginalFilename());
        String path = request.getSession().getServletContext().getRealPath("upload");
        File targetFile = this.imageUploadService.getTargetFile(path,fileName);
        try
        {
            file.transferTo(targetFile);
            this.imageUploadService.uploadImage(fileName, targetFile.getPath());
            model.put("fileUrl", request.getContextPath() + "/upload/" + fileName);
            model.put("file", fileName);
        }
        catch (Exception e)
        {
            logger.error("图片上传失败!", e);
            model.put("errorMsg", "图片上传失败!");
        }
        JSONObject json = JSONObject.fromObject(model);
        response.getWriter().write(json.toString());
        response.getWriter().close();
    }
    
    private String generateFileName(String fileName)  
    {  
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");  
        String formatDate = format.format(new Date());  
        int random = new Random().nextInt(10000);  
        int position = fileName.lastIndexOf(".");  
        String extension = fileName.substring(position);  
        return formatDate + random + extension;  
    } 
2、ImageUploadService如下:
@Service
public class ImageUploadService
{
    
    @Value("${img.server.ip}")
    private String imgServerIp;


    @Value("${img.server.port}")
    private int imgServerPort;


    @Value("${img.server.userName}")
    private String imgServerUserName;


    @Value("${img.server.password}")
    private String imgServerPassword;


    @Value("${img.server.ftpPath}")
    private String imgServerFtpPath;
    
    public void uploadImage(String fileName,String filePath) throws FileNotFoundException, SftpException, JSchException{
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows"))
        {
            FileUtil.sftpUploadImg(imgServerIp, imgServerPort, imgServerUserName, imgServerPassword, imgServerFtpPath, filePath);
        }
        else
        {
            FileUtil.ftpUploadImg(imgServerIp, imgServerPort, imgServerUserName, imgServerPassword, imgServerFtpPath, fileName, filePath);
        }
    }
    
    
    /**
     * 
     * 功能描述:返回File对象
     * @param request
     * @param fileName
     * @return
     */
    public File getTargetFile(String path,String fileName){
        File targetFile = new File(path, fileName);
        if (!targetFile.exists())
        {
            targetFile.mkdirs();
        }
        return targetFile;
    }


}
3、FileUtil如下:
FTP和SFTP的代码都在这个类中。
public class FileUtil
{


    /**
     * 连接sftp服务器
     * 
     * @param host
     *            主机
     * @param port
     *            端口
     * @param username
     *            用户名
     * @param password
     *            密码
     * @return
     * @throws JSchException 
     */
    public static ChannelSftp connect(String host, int port, String username, String password) throws JSchException
    {
        ChannelSftp sftp = null;
        JSch jsch = new JSch();
        jsch.getSession(username, host, port);
        Session sshSession = jsch.getSession(username, host, port);
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        return sftp;
    }




    /**
     * 上传文件
     * 
     * @param directory
     *            上传的目录
     * @param uploadFile
     *            要上传的文件
     * @param sftp
     * @throws SftpException
     * @throws FileNotFoundException
     * @throws JSchException 
     */
    public static void sftpUploadImg(String host, int port, String userName, String password, String directory, String uploadFile) throws FileNotFoundException, SftpException, JSchException
    {
        ChannelSftp sftp = connect(host, port, userName, password);
        sftp.cd(directory);
        File file = new File(uploadFile);
        sftp.put(new FileInputStream(file), file.getName());
    }




    /**
     * 下载文件
     * 
     * @param directory
     *            下载目录
     * @param downloadFile
     *            下载的文件
     * @param saveFile
     *            存在本地的路径
     * @param sftp
     */
    public void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp)
    {
        try
        {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }




    /**
     * 删除文件
     * 
     * @param directory
     *            要删除文件所在目录
     * @param deleteFile
     *            要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp)
    {
        try
        {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    
    /**
     * 
     * 功能描述:ftp上传
     * @param host
     * @param port
     * @param userName
     * @param password
     * @param directory
     * @param uploadFile
     */
    public static void ftpUploadImg(String host, int port, String userName, String password, String directory,String orginalFileName, String uploadFile) { 
        FTPClient ftpClient = new FTPClient(); 
        FileInputStream fis = null; 
        try { 
            ftpClient.connect(host); 
            ftpClient.login(userName, password); 


            File srcFile = new File(uploadFile); 
            fis = new FileInputStream(srcFile); 
            //设置上传目录 
            ftpClient.changeWorkingDirectory(directory); 
            ftpClient.setBufferSize(1024); 
            ftpClient.setControlEncoding("UTF-8"); 
            //设置文件类型(二进制) 
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 
            ftpClient.storeFile(orginalFileName, fis); 
        } catch (IOException e) { 
            e.printStackTrace(); 
            throw new RuntimeException("FTP客户端出错!", e); 
        } finally { 
            IOUtils.closeQuietly(fis); 
            try { 
                ftpClient.disconnect(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
                throw new RuntimeException("关闭FTP连接发生异常!", e); 
            } 
        } 
    } 


}
具体不解释了,自己慢慢看吧。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值