public class UpImgServlet extends HttpServlet ...{ public void destroy() ...{ super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException ...{ response.setContentType("text/html"); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // org.apache.commons.fileupload.DiskFileUpload 是一个开源包里的。 DiskFileUpload du = new DiskFileUpload(); du.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB du.setSizeThreshold(4096);// 设置缓存区大小 ,4 kb; // up 为 /WebRoot 下的 一个目录 du.setRepositoryPath(request.getSession().getServletContext() .getRealPath("/up"));// 设置缓存目录 // 得到所有文件 try ...{ List list = du.parseRequest(request); Iterator it = list.iterator(); while (it.hasNext()) ...{ org.apache.commons.fileupload.FileItem fileItem = (FileItem) it .next(); // 是否为表单元素。如文本框 等等。 if (fileItem.isFormField()) ...{ String name = fileItem.getFieldName();
//通过流 用来读取表单元素里的内容。 java.io.BufferedReader br = new BufferedReader( new InputStreamReader(fileItem.getInputStream()));
楼主【ogoodnight】截止到2008-07-10 19:02:43的历史汇总数据(不包括此帖):
发帖的总数量:0 发帖的总分数:0 每贴平均分数:0
回帖的总数量:0 得分贴总数量:0 回帖的得分率:0%
结贴的总数量:0 结贴的总分数:0
无满意结贴数:0 无满意结贴分:0
未结的帖子数:0 未结的总分数:0
结贴的百分比:---------------------结分的百分比:---------------------
无满意结贴率:---------------------无满意结分率:---------------------
如何结贴请参考这里:http://topic.csdn.net/u/20080501/09/ef7ba1b3-6466-49f6-9d92-36fe6d471dd1.html
用Jsp總時讀取服務器端的文件﹐不知道如何實現在用jsp讀用戶電腦的文件透過FTP上傳。
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{ response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8"); // org.apache.commons.fileupload.DiskFileUpload 是一个开源包里的。
DiskFileUpload du = new DiskFileUpload();
du.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
du.setSizeThreshold(4096);// 设置缓存区大小 ,4 kb;
// up 为 /WebRoot 下的 一个目录
du.setRepositoryPath(request.getSession().getServletContext()
.getRealPath("/up"));// 设置缓存目录 // 得到所有文件
try ...{
List list = du.parseRequest(request);
Iterator it = list.iterator();
while (it.hasNext()) ...{
org.apache.commons.fileupload.FileItem fileItem = (FileItem) it
.next(); // 是否为表单元素。如文本框 等等。
if (fileItem.isFormField()) ...{
String name = fileItem.getFieldName();
//通过流 用来读取表单元素里的内容。
java.io.BufferedReader br = new BufferedReader(
new InputStreamReader(fileItem.getInputStream()));
//如果还有除文件域以外的其他表单元素 就用 if()进行名字一一匹配。
if(name.equals("description"))...{
String contents = br.readLine();
System.out.println(contents);
}
}
// 文件域
else ...{
// 获得文件名,这个文件名包括路径:
String fileName = fileItem.getName();
int index = fileName.lastIndexOf('.');
fileName = fileName.substring(index);
fileName = this.getFileName() + fileName; //文件保存位置
fileItem.write(new File(request.getSession().getServletContext().getRealPath("/img")+ "\" + fileName));
System.out.println("上传成功");
}
} } catch (FileUploadException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
} PrintWriter out = response.getWriter(); out.flush();
out.close();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{
this.doGet(request, response);
} public void init() throws ServletException ...{
// Put your code here
} // 以日期 获得一个文件名。(不重复);
String getFileName() ...{
java.util.Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR);
int mon = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int mi = cal.get(Calendar.MILLISECOND); System.out.println("mon" + mon);
System.out.println("day" + day);
return "" + year + mon + day + hour + min + sec + mi; }}
FTP服务器会指定某个文件夹的话,可以通过SmartUpload的filePath来实现.
下面是jsp代码:<%@ page contentType="text/html;charset=GBK" %>
<%@ page language="java" import="com.jspsmart.upload.*"%>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
boolean foundErr = false;
String errMsg="";
try{
mySmartUpload.initialize(pageContext);
mySmartUpload.setTotalMaxFileSize(1000000);
mySmartUpload.setAllowedFilesList("gif,jpg,jpeg,xls");
mySmartUpload.setDeniedFilesList("exe,bat,jsp,php,doc,txt,asp");
mySmartUpload.upload();
String path = request.getRealPath("../upload/");
for(int i=0;i<mySmartUpload.getFiles().getCount();)
{
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
i++;
if(!myFile.isMissing())
{
if (myFile.getSize()<1024000)
{
if (myFile.getFileExt().toLowerCase().equals("jpg") || myFile.getFileExt().toLowerCase().equals("jpeg") || myFile.getFileExt().toLowerCase().equals("gif"))
{
myFile.saveAs(path+news_id+"_"+i+"."+myFile.getFileExt().toLowerCase());
myFile.saveAs(path+"data"+"."+myFile.getFileExt().toLowerCase());
if(i==1)
{
News.uploadPic(pic,news_id);
}
}
}
}
}
}
catch (Exception e)
{
out.println("Unable to upload the file.<br>");
out.println("Error : " + e.toString());
}
if(foundErr) throw new Exception(errMsg);
out.println("上传成功");
%>然后是SmartUpload.java代码:
[url=http://icekey.ttsite.com/job.php?action-download-pid-tpc-tid-8276156-aid-4270078.html[/url]你试试看吧 应该可以的 这个是好久以前我用过的 呵呵
FTP服务器会指定某个文件夹的话,可以通过SmartUpload的filePath来实现.
下面是jsp代码:<%@ page contentType="text/html;charset=GBK" %>
<%@ page language="java" import="com.jspsmart.upload.*"%>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
boolean foundErr = false;
String errMsg="";
try{
mySmartUpload.initialize(pageContext);
mySmartUpload.setTotalMaxFileSize(1000000);
mySmartUpload.setAllowedFilesList("gif,jpg,jpeg,xls");
mySmartUpload.setDeniedFilesList("exe,bat,jsp,php,doc,txt,asp");
mySmartUpload.upload();
String path = request.getRealPath("../upload/");
for(int i=0;i<mySmartUpload.getFiles().getCount();)
{
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
i++;
if(!myFile.isMissing())
{
if (myFile.getSize()<1024000)
{
if (myFile.getFileExt().toLowerCase().equals("jpg") || myFile.getFileExt().toLowerCase().equals("jpeg") || myFile.getFileExt().toLowerCase().equals("gif"))
{
myFile.saveAs(path+news_id+"_"+i+"."+myFile.getFileExt().toLowerCase());
myFile.saveAs(path+"data"+"."+myFile.getFileExt().toLowerCase());
if(i==1)
{
News.uploadPic(pic,news_id);
}
}
}
}
}
}
catch (Exception e)
{
out.println("Unable to upload the file.<br>");
out.println("Error : " + e.toString());
}
if(foundErr) throw new Exception(errMsg);
out.println("上传成功");
%>然后是SmartUpload.java代码:
[url=http://icekey.ttsite.com/job.php?action-download-pid-tpc-tid-8276156-aid-4270078.html[/url]你试试看吧 应该可以的 这个是好久以前我用过的 呵呵
FTP服务器会指定某个文件夹的话,可以通过SmartUpload的filePath来实现.
下面是jsp代码:<%@ page contentType="text/html;charset=GBK" %>
<%@ page language="java" import="com.jspsmart.upload.*"%>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
boolean foundErr = false;
String errMsg="";
try{
mySmartUpload.initialize(pageContext);
mySmartUpload.setTotalMaxFileSize(1000000);
mySmartUpload.setAllowedFilesList("gif,jpg,jpeg,xls");
mySmartUpload.setDeniedFilesList("exe,bat,jsp,php,doc,txt,asp");
mySmartUpload.upload();
String path = request.getRealPath("../upload/");
for(int i=0;i<mySmartUpload.getFiles().getCount();)
{
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);
i++;
if(!myFile.isMissing())
{
if (myFile.getSize()<1024000)
{
if (myFile.getFileExt().toLowerCase().equals("jpg") || myFile.getFileExt().toLowerCase().equals("jpeg") || myFile.getFileExt().toLowerCase().equals("gif"))
{
myFile.saveAs(path+news_id+"_"+i+"."+myFile.getFileExt().toLowerCase());
myFile.saveAs(path+"data"+"."+myFile.getFileExt().toLowerCase());
if(i==1)
{
News.uploadPic(pic,news_id);
}
}
}
}
}
}
catch (Exception e)
{
out.println("Unable to upload the file.<br>");
out.println("Error : " + e.toString());
}
if(foundErr) throw new Exception(errMsg);
out.println("上传成功");
%>然后是SmartUpload.java代码:
[url=http://icekey.ttsite.com/job.php?action-download-pid-tpc-tid-8276156-aid-4270078.html[/url]你试试看吧 应该可以的 这个是好久以前我用过的 呵呵
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload" %>
<%@ page import="org.apache.commons.fileupload.FileItem" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %><%
String msg = "";
//先创建临时文件夹--保存临时文件
// D:\study\svse\WebRoot\admin_temp_file\
String realPath = this.getServletContext().getRealPath(
"/admin_temp_file/");File f = new File(realPath);
if (!f.exists()) {
f.mkdir();
}
//解析请求
DiskFileUpload dup = new DiskFileUpload();
dup.setHeaderEncoding("utf-8");
try {
List items = dup.parseRequest(request);
Iterator it = items.iterator();
Map fields = new HashMap();
while(it.hasNext()) {
FileItem item =(FileItem)it.next();
if(item.isFormField()) {
fields.put(item.getFieldName(), item.getString());
}else {
fields.put(item.getFieldName(), item);
}
} FileItem upFile = (FileItem)fields.get("adminFile");
//文件路径
String fileUrl = upFile.getName().replace("\\","/");
//分割开
String [] fparts = fileUrl.split("/");
//文件名+.+后缀
String fName = fparts[fparts.length-1];
//文件名
String name = fName.substring(0,fName.lastIndexOf("."));
//后缀
String ext = fName.substring(fName.lastIndexOf(".")+1);
//是否是excel文件,保存
if("xls".equals(ext)) {
File fsave = new File(realPath+"/"+fName);
upFile.write(fsave);
msg="文件解析成功!";
}else {
msg="文件格式错误!必须为Excel文档";
}
} catch (Exception e) {
e.printStackTrace();
msg="解析失败,速速反馈!";
}
request.setAttribute("msg", msg);
request.getRequestDispatcher("/admin/quickadd.jsp").forward(request, response);%>
首先﹐感謝尤斐特和霹靂手不過好像程序都不能達到我的功能﹐我是要將文件上傳到FTP服務器上﹐
不是先上傳到WEB服務器﹐再上傳到FTP服務器上這種方法。
這樣對上傳大文件就沒有意義了
import java.io.PrintWriter;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
public class UploadServlet extends HttpServlet {
public UploadServlet() {
super();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try
{
com.jspsmart.upload.SmartUpload upload =new SmartUpload();
upload.initialize(getServletConfig(), request, response);
upload.setAllowedFilesList("txt,htm,html,rar,zip,jpg,jif,jpeg,xml,,");
upload.setDeniedFilesList("bat,exe,cmd,jsp,class");
upload.setMaxFileSize(1024*1024);//设置单个上传大小1MB
upload.setTotalMaxFileSize(3*1024*1024);//设置总上传大小3MB
upload.upload();
for(int i=0;i<upload.getFiles().getCount();i++)
{
com.jspsmart.upload.File file=upload.getFiles().getFile(i);
if(!file.isMissing())
{
String oldName=file.getFieldName();
String newName=""+System.currentTimeMillis()+(int)(Math.random()*1000)+"."+file.getFileExt();
file.saveAs("/upload/"+newName);
response.getWriter().println(oldName+"-------->"+newName);
response.getWriter().println("<br>");
}
}
com.jspsmart.upload.Request req=upload.getRequest();
String name=req.getParameter("username");
response.getWriter().println("You Type FileName Is:"+name);
response.getWriter().println("Upload Success......");
}catch(Exception e)
{
response.getWriter().println(e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}}
而不是通過先上傳到WEB服務器再轉到FTP服務器上。因目前我們需求﹕
用戶上傳文檔最小都會是150MB﹐用http方式上傳很慢﹐希望通過FTP上傳來保証上傳速度﹐且上傳時部份信息還要寫入資料庫。請問有沒有好的解決方法﹐如果有這樣的組件也可以。
謝謝﹗
http://www.builder.com.cn/2007/1129/660065.shtml建议google一下 java ftp
對用戶來說有點麻煩。
可以实现ftp的大部分功能。// Creating FTP client
FileTransferClient ftp = new FileTransferClient();
ftp.setRemoteHost(host);
ftp.setUserName(username);
ftp.setPassword(password);
ftp.setTimeout(1000 * 60 * 60 * 24);
// connect to the server
ftp.connect();createDirectory(destDir);ftp.uploadFile(file.getAbsolutePath(),fileName.substring(fileName.lastIndexOf("/")+1));ftp.disconnect(true);
也就此结贴,谢谢各位.