fileuploadftp
A. 用java完成圖片多張批量上傳的功能,還有就是後台的應該怎麼處理上傳的照片。
環境准備
1. 下載並安裝Tomcat(已經有很多關於Tomcat安裝以及使用的文章,在這里不再介紹);
2. 下載File upload的jar包commons-fileupload-1.0-beta-1.jar,並將該文件拷貝到{$TOMCAT}/common/lib目錄下(其中{$TOMCAT}為Tomcat的安裝目錄);
3. 由於Fileupload子項目同時要用到另外一個項目commons-Beanutils,所以必須下載Beanutils,並將解壓後的文件commons-beanutils.jar拷貝到{$TOMCAT}/common/lib目錄下。
開發文件上傳頁面
文件上傳的界面如圖1所示。為了增加效率我們設計了三個文件域,同時上傳三個文件。
圖1 文件上傳界面
頁面的HTML代碼如下:
<html>
<head>
<title>文件上傳演示</title>
</head>
<body bgcolor=「#FFFFFF」text=「#000000」 leftmargin=「0」topmargin=「40」marginwidth=「0」 marginheight=「0」>
<center>
<h1>文件上傳演示</h1>
<form name=「uploadform」method=「POST」 action=「save.jsp」ENCTYPE=「multipart/form-data」>
<table border=「1」width=「450」cellpadding=「4」 cellspacing=「2」bordercolor=「#9BD7FF」>
<tr><td width=「100%」colspan=「2」>
文件1:<input name=「file1」size=「40」type=「file」>
</td></tr>
<tr><td width=「100%」colspan=「2」>
文件2:<input name=「file2」size=「40」type=「file」>
</td></tr>
<tr><td width=「100%」colspan=「2」>
文件3:<input name=「file3」size=「40」type=「file」>
</td></tr>
</table>
<br/><br/>
<table>
<tr><td align=「center」><input name=「upload」 type=「submit」value=「開始上傳」/></td></tr>
</table>
</form>
</center>
</body>
</html>
代碼中要特別注意的是黑體處。必須保證表單的ENCTYPE屬性值為multipart/form-data,這樣瀏覽器才能正確執行上傳文件的操作。
處理上傳文件信息
由於本文主要是講述如何使用Commons-fileupload,所以為了便於修改、調試,上傳文件的保存使用一個JSP文件來進行處理。我們將瀏覽器上傳來的所有文件保存在一個指定目錄下並在頁面上顯示所有上傳文件的詳細信息。保存頁面處理結果見圖2所示。
圖2 保存頁面
下面來看看save.jsp的代碼:
<%
/**
* 演示文件上傳的處理
* @author <a href=「mailto:[email protected]」>Winter Lau</a>
* @version $Id: save.jsp,v 1.00 2003/03/01 10:10:15
*/
%>
<%@ page language=「java」contentType=「text/html;charset=GBK」%>
<%@ page import=「java.util.*」%>
<%@ page import=「org.apache.commons.fileupload.*」%>
<html>
<head>
<title>保存上傳文件</title>
</head>
<%
String msg = 「」;
FileUpload fu = new FileUpload();
// 設置允許用戶上傳文件大小,單位:位元組
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(「C:\\TEMP」);
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
%>
<body bgcolor=「#FFFFFF」text=「#000000」 leftmargin=「0」topmargin=「40」marginwidth=「0」 marginheight=「0」>
<font size=「6」color=「blue」>文件列表:</font>
<center>
<table cellpadding=0 cellspacing=1 border=1 width=「100%」>
<tr>
<td bgcolor=「#008080」>文件名</td>
<td bgcolor=「#008080」>大小</td>
</tr>
<%
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
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;
%>
<tr>
<td><%=item.getName()%></td>
<td><%=item.getSize()%></td>
</tr>
<%
//保存上傳的文件到指定的目錄
name = name.replace(『:』,『_』);
name = name.replace(『\\』,『_』);
item.write(「F:\\」+ name);
}
}
%>
</table>
<br/><br/>
<a href=「upload.html」>返回上傳頁面</a>
</center>
</body>
</html>
在這個文件中需要注意的是FileUpload對象的一些參數值的意義,如下面代碼所示的三個參數sizeMax、sizeThreshold、repositoryPath:
FileUpload fu = new FileUpload();
// 設置允許用戶上傳文件大小,單位:位元組
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(「C:\\TEMP」);
這3個參數的意義分別為:
SizeMax 用來設置上傳文件大小的最大值,一旦用戶上傳的文件大小超過該值時將會拋出一個FileUploadException異常,提示文件太大;
SizeThreshold 設置內存中緩沖區的大小,一旦文件的大小超過該值的時候,程序會自動將其它數據存放在repositoryPath指定的目錄下作為緩沖。合理設置該參數的值可以保證伺服器穩定高效的運行;
RepositoryPath 指定緩沖區目錄。
使用注意事項
從實際應用的結果來看該模塊能夠穩定高效的工作。其中參數SizeThreshold的值至關重要,設置太大會佔用過多的內存,設置太小會頻繁使用硬碟作為緩沖以致犧牲性能。因此,設置該值時要根據用戶上傳文件大小分布情況來設定。例如大部分文件大小集中在100KB左右,則可以使用100KB作為該參數的值,當然了再大就不合適了。使用commons-fileupload來處理HTTP文件上傳的功能模塊很小,但是值得研究的東西很多。
B. 如何用Apache 的fileupload 將文件上傳到另一台電腦
stem.out.println("size limit exception!");
} catch(Exception e) { e.printStackTrace();
} Iterator iter = items==null?null:items.iterator();
while(iter != null &&
iter.hasNext()) { FileItem item = (FileItem)iter.next();
//簡單的表單域 if(item.isFormField()) { System.out.print("form field:");
System.out.print(item.getFieldName() + " ");
System.out.print(item.getString());
} //文件域 else if(!item.isFormField()) { System.out.println("client name:" + item.getName());
String fileName = item.getName().substring(item.getName().lastIndexOf("\\"));
BufferedInputStream in = new BufferedInputStream(item.getInputStream());
//文件存儲在工程的upload目錄下,這個目錄也得存在 BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File("../webapps/fileupload/upload/" + fileName)));
Streams.(in, out, true);
} } } else { System.out.println("enctype error!");
} } }
因為使用tomcat做得伺服器,所以裡面的路徑都是以tomcat為基礎來寫得,具體情況需要修改。
stem.out.println("size limit exception!");
} catch(Exception e) { e.printStackTrace();
} Iterator iter = items==null?null:items.iterator();
while(iter != null &&
iter.hasNext()) { FileItem item = (FileItem)iter.next();
//簡單的表單域 if(item.isFormField()) { System.out.print("form field:");
System.out.print(item.getFieldName() + " ");
System.out.print(item.getString());
} //文件域 else if(!item.isFormField()) { System.out.println("client name:" + item.getName());
String fileName = item.getName().substring(item.getName().lastIndexOf("\\"));
BufferedInputStream in = new BufferedInputStream(item.getInputStream());
//文件存儲在工程的upload目錄下,這個目錄也得存在 BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(new File("../webapps/fileupload/upload/" + fileName)));
Streams.(in, out, true);
} } } else { System.out.println("enctype error!");
} } }
因為使用tomcat做得伺服器,所以裡面的路徑都是以tomcat為基礎來寫得,具體情況需要修改。
C. 你是怎麼解決ftp上傳失敗的
jfileupload applet我之前用的是這個很古老的東西來做文件上傳,遇到這個問題。後來只得換了另外一種做法。你是要做FTP文件上傳嗎?如果是的話像我這樣做,代碼:
public static boolean 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之後文件內容會出錯*/
ftp.setControlEncoding("GBK");
//設置文件類型(二進制)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
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;
}
D. javaWeb能和ftp實現大文件上傳嗎
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/html; charset=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=0;temp 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);
}
}
}
E. fileupload控制項可以從瀏覽框的地址欄訪問ftp嗎怎麼好像不可以的樣子
FTP是文件檢索,可以快速打開一個文件,FTP只能輸入在我的電腦地址欄。
F. ASP.NET用FileUpload上傳圖片在本地可以,上傳FTP伺服器出錯,請問這是怎麼回事啊
一般情況是路勁的問題。
G. 請教大師們,FileUpload的文件怎麼指定路徑都上傳到哪了呢,如果是ftp,需要密碼嗎
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="up" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>無標題頁</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<input id="Button1" runat="server" onserverclick="Button1_ServerClick" type="button"
value="上傳" /></div>
</form>
</body>
</html>
//Code:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class up : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_ServerClick(object sender, EventArgs e)
{
//取得字元串:「C:\Documents and Settings\Administrator\Desktop\picture\213.jpg」
string fileName = this.FileUpload1.PostedFile.FileName;
//取得從開始到最後一個「\」得長度:fileName.LastIndexOf("\\")
int length = fileName.Length - fileName.LastIndexOf("\\") - 1;
//截取從fileName.LastIndexOf("\\") + 1位置到length位置的字元串
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1, length);
//取得字元串:「C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite1\upload2\」
string path = Server.MapPath("upload2\\");
//判斷有沒有path的文件,如果沒有則創建一個新的
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//取得文件的後綴名:「.jpg 」
string s1 = System.IO.Path.GetExtension(fileName);
//取得Web.Config中 <appSettings><add key="conn" value="2048"/></appSettings>配置的值
string s2=System.Configuration.ConfigurationManager.AppSettings["conn"];
//取得上傳的文件的大小,單位為bytes
int filesize = (FileUpload1.PostedFile.ContentLength) / 1024;
if (s1 == ".jpg" || s1 == ".gif")
{
//如果文件大小<設定大小,則上傳文件到:C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite1\upload2\213.jpg
if (filesize < Convert.ToInt32(s2))
{
FileUpload1.PostedFile.SaveAs(path + fileName);
}
else
{
Response.Write("<script>alert('太大了')</script>");
}
}
else
{
Response.Write("<script>alert('請選擇JPG或GIF格式的文件')</script>");
}
}
}