『壹』 求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);*/
}
}