ftp上传文件(并解决了文件上传中应中文标题没有转换而导致上传失败的问题等)

代码示例:

/**
     * 上传文件
     * 
     * @param P_Files
     */
    public static void uploadFile(File P_File)
    {
        if (P_File.exists())
        {
            String strFtpIp = getFtpIp();
            String strUserName = getFtpUserName();
            String strPassword = getFtpPassword();
            FTPClient ftpClient = new FTPClient();
            FileInputStream fis = null;
            try
            {
                // 连接服务
                ftpClient.connect(strFtpIp);
                ftpClient.login(strUserName, strPassword);
                // 获取临时文件
                // 文件路径加上temp的目的是为了每次上传的附件不被覆盖,使用filename的目的是为了和数据库保存的文件名是一样的,这样能够根据数据库中的文件名称获取到附件
                String preFileName = P_File.getName();
                if (preFileName != null && preFileName.length() > 0)
                {
                    fis = new FileInputStream(P_File);
                    // 表示获取的文件流是大于0字节以上
                    if (fis.available() > 0)
                    {
                        ftpClient.setBufferSize(1024);// 设置1M缓冲
                        ftpClient.setControlEncoding("GBK");// 设置编码为GBK
                        // 设置文件类型(二进制)
                        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                        if (ftpClient.storeFile(new String(preFileName.getBytes("GBK"), "iso-8859-1"), fis))
                        {
                            System.out.println(preFileName + "通过ftp上传成功");
                        }
                        else
                        {
                            System.out.println(preFileName + "通过ftp上传失败");
                        }
                    }
                    else
                    {
                        System.out.println("fis is null,filepath=" + P_File.getPath());
                    }
                }

            }
            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);
                }
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/EscapePlan/article/details/88239231
今日推荐