使用一些已有的组件帮助我们实现这种
上传功能。常用的上传组件:Apache 的 Commons FileUploadJavaZoom的UploadBeanjspSmartUpload以下,以FileUpload为例讲解1、在jsp端<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">要注意enctype="multipart/form-data"然后只需要放置一个file控件,并执行submit操作即可<input name="file" type="file" size="20" ><input type="submit" name="submit" value="提交" >2、web端核心
代码如下:public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8") DiskFileItemFactory factory = new DiskFileItemFactory() ServletFileUpload upload = new ServletFileUpload(factory) try { List items = upload.parseRequest(request) Iterator itr = items.iterator() while (itr.hasNext()) {FileItem item = (FileItem) itr.next()if (item.isFormField()) { System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"))} else { if (item.getName() != null &&!item.getName().equals("")) { System.out.println("
上传文件的大小:" + item.getSize()) System.out.println("上传文件的类型:" + item.getContentType()) System.out.println("上传文件的名称:" + item.getName()) File tempFile = new File(item.getName()) File file = new File(sc.getRealPath("/") + savePath, tempFile.getName()) item.write(file) request.setAttribute("upload.message", "上传文件成功!") }else{ request.setAttribute("upload.message", "没有选择上传文件!") }} } }catch(FileUploadException e){ e.printStackTrace() } catch (Exception e) { e.printStackTrace() request.setAttribute("upload.message", "上传文件失败!") } request.getRequestDispatcher("/uploadResult.jsp").forward(request, response) }android客户端实现FTP文件需要用到 commons-net-3.0.1.jar
先将jar包复制到android libs目录下
复制以下实现代码
以下为实现代码:
/**
* 通过ftp上传文件
* @param url ftp服务器地址 如:
* @param port 端口如 :
* @param username 登录名
* @param password 密码
* @param remotePath 上到ftp服务器的磁盘路径
* @param fileNamePath 要上传的文件路径
* @param fileName 要上传的文件名
* @return
*/
public String ftpUpload(String url, String port, String username,String password, String remotePath, String fileNamePath,String fileName) {
FTPClient ftpClient = new FTPClient()
FileInputStream fis = null
String returnMessage = "0"
try {
ftpClient.connect(url, Integer.parseInt(port))
boolean loginResult = ftpClient.login(username, password)
int returnCode = ftpClient.getReplyCode()
if (loginResult &&FTPReply.isPositiveCompletion(returnCode)) {// 如果登录成功
ftpClient.makeDirectory(remotePath)
// 设置上传目录
ftpClient.changeWorkingDirectory(remotePath)
ftpClient.setBufferSize(1024)
ftpClient.setControlEncoding("UTF-8")
ftpClient.enterLocalPassiveMode()
fis = new FileInputStream(fileNamePath + fileName)
ftpClient.storeFile(fileName, fis)
returnMessage = "1" //上传成功
} else {// 如果登录失败
returnMessage = "0"
}
} 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)
}
}
return returnMessage
}
评论列表(0条)