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>");
}
}
}