java ftpclient怎么传输多个文件?

java ftpclient怎么传输多个文件?,第1张

/**

* Description: 向FTP服务器上传文件

* @Version1.0 Jul 27, 2008 4:31:09 PM by 崔红保([email protected])创建

* @param url FTP服务器hostname

* @param port FTP服务器端口

* @param username FTP登录账号

* @param password FTP登录密码

* @param path FTP服务器保存目录

* @param filename 上传到FTP服务器上的文件

* @param input 输入流

* @return 成功返回true,否则返回false

*/

publicstaticboolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {

boolean success = false

FTPClient ftp = new FTPClient()

try {

int reply

ftp.connect(url, port)//连接FTP服务器

//如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

ftp.login(username, password)//登录

reply = ftp.getReplyCode()

if (!FTPReply.isPositiveCompletion(reply)) {

ftp.disconnect()

return success

}

ftp.changeWorkingDirectory(path)

ftp.storeFile(filename, input)

input.close()

ftp.logout()

success = true

} catch (IOException e) {

e.printStackTrace()

} finally {

if (ftp.isConnected()) {

try {

ftp.disconnect()

} catch (IOException ioe) {

}

}

}

return success

}<pre></pre>

java上传可以使用common-fileupload上传组件的。common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件下面先介绍上传文件到服务器(多文件上传):import javax.servlet.*

import javax.servlet.http.*

import java.io.*

import java.util.*

import java.util.regex.*

import org.apache.commons.fileupload.*

public class upload extends HttpServlet {

private static final String CONTENT_TYPE = "text/htmlcharset=GB2312"

//Process the HTTP Post request

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType(CONTENT_TYPE)

PrintWriter out=response.getWriter()

try {

DiskFileUpload fu = new DiskFileUpload()

// 设置允许用户上传文件大小,单位:字节,这里设为2m

fu.setSizeMax(2*1024*1024)

// 设置最多只允许在内存中存储的数据,单位:字节

fu.setSizeThreshold(4096)

// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

fu.setRepositoryPath("c:\\windows\\temp")

//开始读取上传信息

List fileItems = fu.parseRequest(request)

// 依次处理每个上传的文件

Iterator iter = fileItems.iterator()//正则匹配,过滤路径取文件名

String regExp=".+\\\\(.+)$"//过滤掉的文件类型

String[] errorType={".exe",".com",".cgi",".asp"}

Pattern p = Pattern.compile(regExp)

while (iter.hasNext()) {

FileItem item = (FileItem)iter.next()

//忽略其他不是文件域的所有表单信息

if (!item.isFormField()) {

String name = item.getName()

long size = item.getSize()

if((name==null||name.equals("")) &&size==0)

continue

Matcher m = p.matcher(name)

boolean result = m.find()

if (result){

for (int temp=0temp if (m.group(1).endsWith(errorType[temp])){

throw new IOException(name+": wrong type")

}

}

try{//保存上传的文件到指定的目录//在下文中上传文件至数据库时,将对这里改写

item.write(new File("d:\\" + m.group(1))) out.print(name+" "+size+"

")

}

catch(Exception e){

out.println(e)

}}

else

{

throw new IOException("fail to upload")

}

}

}

}

catch (IOException e){

out.println(e)

}

catch (FileUploadException e){

out.println(e)

}

}

}

即使再多文件也是通过的单个文件逐次上传的(zip等压缩包实际上是一个文件)。实现思路就是将多个文件循环进行上传,上传方法举例:

/**

* 上传文件

*

* @param fileName

* @param plainFilePath 文件路径路径

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null

ByteArrayOutputStream bos = null

FTPClient ftpClient = new FTPClient()

String bl = "false"

try {

fis = new FileInputStream(plainFilePath)

bos = new ByteArrayOutputStream(fis.available())

byte[] buffer = new byte[1024]

int count = 0

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count)

}

bos.flush()

Log.info("加密上传文件开始")

Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22)

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22)

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD)

FTPFile[] fs

fs = ftpClient.listFiles()

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl="true"

ftpClient.changeWorkingDirectory("/"+filepath+"")

}

}

Log.info("检查文件路径是否存在:/"+filepath)

if("false".equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath)

return bl

}

ftpClient.setBufferSize(1024)

ftpClient.setControlEncoding("GBK")

// 设置文件类型(二进制)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE)

ftpClient.storeFile(fileName, fis)

Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/")

return bl

} catch (Exception e) {

throw e

} finally {

if (fis != null) {

try {

fis.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

if (bos != null) {

try {

bos.close()

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e)

}

}

}

}

备注:只需要修改上传的服务器地址、用户名、密码即可进行服务器访问上传。根据实际需要修改即可。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12037754.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-20
下一篇 2023-05-20

发表评论

登录后才能评论

评论列表(0条)

保存