『壹』 求java web 实现的文件上传代码 用开发环境是myeclipse
这个例子
下载:commons-fileUpload-1.2 的jar包:http://www.apache.org/commons/,同时可以把commons-IO的jar包一起下载,以后会用到的。
1、上传的前台页面:
<%@pagelanguage="java"import="java.util.*"contentType="text/html;charset=gbk" pageEncoding="gbk"%> <html> <body>
<form action="MultipartTestServlet" enctype="multipart/form-data" method="post">
<input type="text" name="username" /><br /> <input type="file" name="myfile" /><br/> <input type="file" name="myfile" /><br/> <input type="submit" /> </form> </body> </html>
2、上传的后台代码:
后台代码是个servlet,很简单咯,觉得比ASP利用组件还简单。呵呵 package upload;
import java.io.File;
import java.io.IOException; import java.util.ArrayList
; import java.util.Iterator; import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
public class MultipartTestServlet extends HttpServlet {
public MultipartTestServlet() { super(); }
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置request编码,主要是为了处理普通输入框中的中文问题 request.setCharacterEncoding("gbk");
//这里对request进行封装,RequestContext提供了对request多个访问方法 RequestContext requestContext = new ServletRequestContext(request); //判断表单是否是Multipart类型的。这里可以直接对request进行判断,不过已经以前的用法了
if(FileUpload.isMultipartContent(requestContext)){
DiskFileItemFactory factory = new DiskFileItemFactory(); //设置文件的缓存路径
factory.setRepository(new File("c:/tmp/"));
ServletFileUpload upload = new ServletFileUpload(factory); //设置上传文件大小的上限,-1表示无上限 upload.setSizeMax(100*1024*1024); List items = new ArrayList(); try {
//上传文件,并解析出所有的表单字段,包括普通字段和文件字段 items = upload.parseRequest(request); } catch (FileUploadException e1) {
System.out.println("文件上传发生错误" + e1.getMessage()); }
//下面对每个字段进行处理,分普通字段和文件字段 Iterator it = items.iterator(); while(it.hasNext()){
FileItem fileItem = (FileItem) it.next(); //如果是普通字段
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk")); }else{
System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + fileItem.isInMemory() + " " + fileItem.getContentType() + " " + fileItem.getSize());
//保存文件,其实就是把缓存里的数据写到目标路径下 if(fileItem.getName()!=null && fileItem.getSize()!=0){ File fullFile = new File(fileItem.getName());
File newFile = new File("c:/temp/" + fullFile.getName()); try {
fileItem.write(newFile); } catch (Exception e) { e.printStackTrace(); } }else{
System.out.println("文件没有选择 或 文件内容为空"); } } } } } }
3、编译和配置servlet
先设置classpath,使它包含commons-fileUpload的jar包路径,然后进行编译即可,注意这里的包路径。
然后打开站点下的web-inf路径下的web.xml,在里面添加: <servlet>
<servlet-name>MultipartTestServlet</servlet-name>
<servlet-class>upload.MultipartTestServlet</servlet-class> </servlet> <servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>helloApp.DispatcherServlet</servlet-class> </servlet>
好了,现在就可以文件上传了,不过运行之前记得在c:/下新建tmp和temp文件夹,别忘了,不然程序会报告错误的。
『贰』 请教Java怎样实现跨服务器文件上传
你好!
另一台机器也要有处理文件上传的WEB程序,你可以参考Stream上传插件(支持HTML5和Flash两种方式上传)
Stream 上传插件
Stream 是解决不同浏览器上传文件的插件,是Uploadify的Flash版和Html5版的结合!
Stream 简介
Stream 是根据某网的文件上传插件加工而来,支持不同平台(Windows, Linux, Mac, Android, iOS)下,主流浏览器(IE7+, Chrome, Firefox, Safari, 其他)的上传工作,当然在Html5标准下,还支持文件的断点续传功能,有效解决大文件的Web上传问题!
主要特征
1. 源码完全开放,目前有Java、PHP、Perl三种后台语言实现
2. 支持HTML5、Flash两种方式(跨域)上传
3. 多文件一起上传
4. HTML5支持断点续传,拖拽等新特性
5. 兼容性好IE7+, FF3.6+, Chrome*,Safari4+,遨游等主流浏览器
6. 进度条、速度、剩余时间等附属信息
7. `选择文件的按钮`可以自定义
8. 简单的参数配置实现 灵活多变的功能
9. 支持文件夹上传(Chrome21+, Opera15+)
10. 支持自定义UI(V1.4+)
指定跨域上传就可以了
这些都是小鸟云的工程师告诉我的,建议你可以试试小鸟云
『叁』 java编程:怎么用JSP(javabean)上传一张图片到服务器的指定文件夹呢
网络,想飞社区,在资讯里,找 WEB前端 分类,有一篇文章:AJAX JAVA 上传文件,可以参考,抱歉,贴不了地址。。。我只能这样说了
『肆』 java 实现ftp上传如何创建文件夹
这个功能我也刚写完,不过我也是得益于同行,现在我也把自己的分享给大家,希望能对大家有所帮助,因为自己的项目不涉及到创建文件夹,也仅作分享,不喜勿喷谢谢!
interface:
packagecom.sunline.bank.ftputil;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;
publicinterfaceIFtpUtils{
/**
*ftp登录
*@paramhostname主机名
*@paramport端口号
*@paramusername用户名
*@parampassword密码
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主机名
*@paramport端口号
*@paramusername用户名
*@parampassword密码
*@paramfpathftp路径
*@paramlocalpath本地路径
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下载文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*关闭流连接、ftp连接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}
impl:
packagecom.sunline.bank.ftputil;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;
{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;
@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//设置文件类型为二进制(避免解压缩文件失败)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//开通数据端口传输数据,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("连接FTP失败,用户名或密码错误");
}else{
log.info("FTP连接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登录FTP失败,请检查FTP相关配置信息是否正确",e1);
}
}
}
returnftpClient;
}
@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上传失败");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上传成功");
}
returnfalse;
}
@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切换到当前目录
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;
}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下载成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}
@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夹是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,请检查。。。");
}
}
}
}
}
@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下载/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}