怎么在jsp页面实现文件上传呢 这个需求只能借助于控件来实现。因为JS没有访问本地硬盘文件的权限。IE,Firefrox,Chrome都做了权限限制。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 楼主试试这个控件:http://www.cnblogs.com/xproer/archive/2010/10/24/1859895.html此控件是基于标准HTTP协议实现的文件上传功能。优势是扩展性非常好,整合简单,支持批量上传文件和上传文件夹功能,上传前获取本地文件大小,适合各种简单WEB项目。另外一个特点是支持自动上传指定的本地文件。单文件上传演示上传本地文件代码使用步骤如下:1.调用AddFile函数添加本地文件,注意路径需要使用双斜框(\\)2.调用PostFirst函数开始上传文件。<script type="text/javascript" language="javascript"> var fileMgr = new HttpUploaderMgr(); fileMgr.Load();//加载控件 window.onload = function() { fileMgr.Init();//初始化控件 //添加一个本地文件 fileMgr.AddFile("D:\\Soft\\QQ2010.exe"); fileMgr.PostFirst(); };</script>获取本地文件大小 服务器返回消息:<input id="txtFilePath" type="text" size="50" /> <script type="text/javascript" language="javascript"> var fileMgr = new HttpUploaderSingleMgr(); fileMgr.Config["PostUrl"] = "http://localhost:8080/asp.net/upload.aspx";//指定文件上传地址,可以在这里设置文件服务器地址 fileMgr.Load(); function testFileSize() { var obj = new ActiveXObject(fileMgr.ActiveX["Partition"]); alert(obj.FileSize("D:\\VS2012.SP4.iso")); } function testFileLength() { var obj = new ActiveXObject(fileMgr.ActiveX["Partition"]); alert(obj.FileLength("D:\\VS2012.SP4.iso")); } </script>单文件整合代码: 服务器返回消息:<input id="txtFilePath" type="text" size="50" /> <script type="text/javascript" language="javascript"> var fileMgr = new HttpUploaderSingleMgr(); fileMgr.Config["PostUrl"] = "http://localhost:8080/asp.net/upload.aspx";//指定文件上传地址,可以在这里设置文件服务器地址 fileMgr.Load(); //文件上传完成后执行的回调函数 fileMgr.CompleteHook = function(msg) { document.getElementById("txtFilePath").value = msg; }; window.onload = function() { fileMgr.Init(); }; </script>示例下载:cab安装包(x86)cab安装包(x64)xpi安装包crx安装包exe安装包开发文档ASP示例ASP.NET示例JSP示例PHP示例 upload.jsp代码;<%@ page language="java" contentType="text/html; charset=UTF-8"%><html><head><title>using commons Upload to upload file </title></head><style>* { font-family: "宋体"; font-size: 14px }</style><body><p align="center"> 请您选择需要上传的文件</p><form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"> <table border="0" align="center"> <tr> <td>上传人:</td> <td> <input name="name" type="text" id="name" size="20" ></td> </tr> <tr> <td>上传文件:</td> <td><input name="file" type="file" size="20" ></td> </tr> <tr> <td></td><td> <input type="submit" name="submit" value="提交" > <input type="reset" name="reset" value="重置" > </td> </tr> </table></form></body></html>--------------------------------------------------------------------------------------------------FileUploadServlet.java代码:/** * */package com.b510.example;import java.io.File;import java.io.IOException;import java.util.*;import javax.servlet.ServletConfig;import javax.servlet.ServletContext;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * * @author XHW * * @date 2011-7-26 * */public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = -7744625344830285257L; private ServletContext sc; private String savePath; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void init(ServletConfig config) { // 在web.xml中设置的一个初始化参数 savePath = config.getInitParameter("savePath"); sc = config.getServletContext(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8")); } else { if (item.getName() != null && !item.getName().equals("")) { System.out.println("上传文件的大小:" + item.getSize()); System.out.println("上传文件的类型:" + item.getContentType()); // item.getName()返回上传文件在客户端的完整路径名称 System.out.println("上传文件的名称:" + item.getName()); File tempFile = new File(item.getName()); //上传文件的保存路径 File file = new File(sc.getRealPath("/") + savePath, tempFile.getName()); item.write(file); request.setAttribute("upload.message", "上传文件成功!"); }else{ request.setAttribute("upload.message", "没有选择上传文件!"); } } } }catch(FileUploadException e){ e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); request.setAttribute("upload.message", "上传文件失败!"); } request.getRequestDispatcher("/uploadResult.jsp").forward(request, response); }}--------------------------------------------------------------------------------------------------uploadResult.jsp代码;<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>uploadResult</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> ${requestScope['upload.message'] } <a href="/upload/uploadFile.jsp">上传文件</a> </body></html>--------------------------------------------------------------------------------------------------web.xml代码:<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>com.b510.example.FileUploadServlet</servlet-class> <!--设置初始化参数--> <init-param> <param-name>savePath</param-name> <param-value>uploads</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/servlet/fileServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>uploadFile.jsp</welcome-file> </welcome-file-list></web-app> 如果是指定路径的话,就只能用控件来实现。如果让用户选择的话就用input[type=file]。楼上朋友推荐的Xproer.HttpUploader2不错。看起来挻强大的。我们公司做的一个项目也有这个需求,打算换这个控件来试试。 tomcat 启动时候 hibernate Util类的写法 Hibernate模糊查询 Tomcat错误 jboss支持热部署么? jsp问题 如何用java来获取某一文件属性中的摘要信息? 如何在一个JAVA程序中执行(启动)另外一个JAVA程序? 关于RPC,Document,Soap Message,Literal XML 想通过一个servlet传参数运行一个main函数 求指点 json字符数组怎么去掉(替换)空值null? Spring Task
此控件是基于标准HTTP协议实现的文件上传功能。优势是扩展性非常好,整合简单,支持批量上传文件和上传文件夹功能,上传前获取本地文件大小,适合各种简单WEB项目。
另外一个特点是支持自动上传指定的本地文件。单文件上传演示上传本地文件代码
使用步骤如下:
1.调用AddFile函数添加本地文件,注意路径需要使用双斜框(\\)
2.调用PostFirst函数开始上传文件。<script type="text/javascript" language="javascript">
var fileMgr = new HttpUploaderMgr();
fileMgr.Load();//加载控件 window.onload = function()
{
fileMgr.Init();//初始化控件
//添加一个本地文件
fileMgr.AddFile("D:\\Soft\\QQ2010.exe");
fileMgr.PostFirst(); };
</script>
获取本地文件大小 服务器返回消息:<input id="txtFilePath" type="text" size="50" />
<script type="text/javascript" language="javascript">
var fileMgr = new HttpUploaderSingleMgr();
fileMgr.Config["PostUrl"] = "http://localhost:8080/asp.net/upload.aspx";//指定文件上传地址,可以在这里设置文件服务器地址
fileMgr.Load();
function testFileSize()
{
var obj = new ActiveXObject(fileMgr.ActiveX["Partition"]);
alert(obj.FileSize("D:\\VS2012.SP4.iso"));
} function testFileLength()
{
var obj = new ActiveXObject(fileMgr.ActiveX["Partition"]);
alert(obj.FileLength("D:\\VS2012.SP4.iso"));
}
</script>
单文件整合代码: 服务器返回消息:<input id="txtFilePath" type="text" size="50" />
<script type="text/javascript" language="javascript">
var fileMgr = new HttpUploaderSingleMgr();
fileMgr.Config["PostUrl"] = "http://localhost:8080/asp.net/upload.aspx";//指定文件上传地址,可以在这里设置文件服务器地址
fileMgr.Load();
//文件上传完成后执行的回调函数
fileMgr.CompleteHook = function(msg)
{
document.getElementById("txtFilePath").value = msg;
}; window.onload = function()
{
fileMgr.Init();
};
</script>示例下载:
cab安装包(x86)
cab安装包(x64)
xpi安装包
crx安装包
exe安装包
开发文档
ASP示例
ASP.NET示例
JSP示例
PHP示例
<html>
<head>
<title>using commons Upload to upload file </title>
</head>
<style>
* { font-family: "宋体"; font-size: 14px }
</style>
<body>
<p align="center"> 请您选择需要上传的文件</p>
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
<table border="0" align="center">
<tr>
<td>上传人:</td>
<td>
<input name="name" type="text" id="name" size="20" ></td>
</tr>
<tr>
<td>上传文件:</td>
<td><input name="file" type="file" size="20" ></td>
</tr>
<tr>
<td></td><td>
<input type="submit" name="submit" value="提交" >
<input type="reset" name="reset" value="重置" >
</td>
</tr>
</table>
</form>
</body>
</html>--------------------------------------------------------------------------------------------------FileUploadServlet.java代码:/**
*
*/
package com.b510.example;import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;/**
*
* @author XHW
*
* @date 2011-7-26
*
*/
public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = -7744625344830285257L;
private ServletContext sc;
private String savePath; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void init(ServletConfig config) {
// 在web.xml中设置的一个初始化参数
savePath = config.getInitParameter("savePath");
sc = config.getServletContext();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
// item.getName()返回上传文件在客户端的完整路径名称
System.out.println("上传文件的名称:" + item.getName()); File tempFile = new File(item.getName()); //上传文件的保存路径
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}else{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
}--------------------------------------------------------------------------------------------------uploadResult.jsp代码;<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>uploadResult</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head>
<body>
${requestScope['upload.message'] }
<a href="/upload/uploadFile.jsp">上传文件</a>
</body>
</html>--------------------------------------------------------------------------------------------------web.xml代码:<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.b510.example.FileUploadServlet</servlet-class> <!--设置初始化参数-->
<init-param>
<param-name>savePath</param-name>
<param-value>uploads</param-value>
</init-param>
</servlet> <servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/servlet/fileServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>uploadFile.jsp</welcome-file>
</welcome-file-list>
</web-app>