以下内容引用自http://wiki.jikexueyuan.com/project/jsp/file-uploading.html

一个JSP可以用一个HTML表单标签,它允许用户上传文件到服务器。上传的文件是一个文本文件或二进制文件,图像文件或任何文件。

一、创建文件上传形式

用下面的HTM代码创建一个上传表单。以下的要点应该记下来:

  • 表单method的属性应该设置为POST方法,不能使用GET方法。
  • 表单enctype的属性应该设置为multipart/formdata。

  • 表单action的属性应该设置为一个把文件上传到后台服务器的JSP文件。下面的例子是使用程序uploadFile.jsp来上传文件。

  • 为了上传一个单一的文件,应该使用一个带有属性type="file"的<input .../>标签。为了允许多个文件上传,包含多个输入标签,它们带有不同的name属性的值。浏览器将浏览按钮与每个输入标签进行关联。

示例:

前台main.html

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadFile.jsp" method="post" enctype="multipart/form-data">
  <input type="file" name="file" size="50" />
  <br />
  <input type="submit" value="Upload File" />
</form>
</body>
</html>

后台UploadFile.jsp

首先,定义一个上传文件要存储的位置。可以在程序中进行硬编码或该目录名称也可以使用外部配置来添加,如在web.xml的context-param元素中,如下所示:

<web-app>
....
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:\apache-tomcat-5.5.29\webapps\data\
</param-value>
</context-param>
....
</web-app>

下面是UploadFile.jsp的源代码,它可以一次上传多个文件。处理开始之前,应该确保下列事项:

  • 下面的例子取决于FileUpload,所以确保在classpath中有最新的版本commons-fileupload.x.x.jar文件。可以从http://commons.apache.org/fileupload/中下载它。

  • FileUpload取决于Commons IO,所以确保在classpath中有最新的版本commons-io-x.x.jar文件。可以从http://commons.apache.org/io/中下载它。

  • 当测试下面的例子时,应该上传小于maxFileSize的文件,否则文件不能上传。

  • 确保提前创建好目录c:\temp和c:\apache-tomcat-5.5.29\webapps\data。
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%
File file ;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
// Verify the content type
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>JSP File upload</title>");
out.println("</head>");
out.println("<body>");
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
file = new File( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
out.println("Uploaded Filename: " + filePath +
fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
}catch(Exception ex) {
System.out.println(ex);
}
}else{
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
}
%>

现在尝试用上面创建的HTML表单来上传文件。当运行http://localhost:8080/main.htm,它将显示如下结果:

如果JSP script运行良好,文件应该上传到c:\apache-tomcat-5.5.29\webapps\data\directory 中。

测试工程:https://github.com/easonjim/5_java_example/tree/master/jspbasics/test11

JSP的文件上传的更多相关文章

  1. JSP多文件上传到服务器

    问题描述: 作为一个Java开发Web方向的程序员,很重要的一个功能,就是上传文件功能是一定要掌握的,今天整理了一下代码. 1.JSP显示界面代码和动态添加上传文件个数. <%@ page la ...

  2. Android+jsp +html 文件上传案例 已测试 成功通过

    我文件上传一直是广大读者一个问题 今天就把成功案例写下 javaweb 网页前段 <%@ page language="java" import="java.uti ...

  3. 基于jsp的文件上传和下载

    参考: 一.JavaWeb学习总结(五十)--文件上传和下载 此文极好,不过有几点要注意: 1.直接按照作者的代码极有可能listfile.jsp文件中 <%@taglib prefix=&qu ...

  4. jsp简易文件上传(common.fileupload)

    昨天开始重新架构我的V&View(维视),之前写文章使用的是一个kindediter的插件,挺好用的.最近不知道咋了,出现了些小问题.早在写V&View的时候就想用以下两种方法实现文章 ...

  5. jsp Servlet 文件上传

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  6. jsp实现文件上传下载

    文件上传: upload.jsp <form action="uploadServlet" method="post" enctype="mul ...

  7. 使用jsp实现文件上传的功能

    首先是表单的jsp文件:upload.jsp <%@ page contentType="text/html;charset=UTF-8" language="ja ...

  8. jsp实现文件上传(二)用cos组件实现文件上传

    jsp表单 <%@ page language="java" pageEncoding="utf-8"%> <html> <hea ...

  9. JSP入门 文件上传

    commons-fileupload public void save(HttpServletRequest request,HttpServletResponse response) throws ...

随机推荐

  1. iOS programming Code Snippet Library

    iOS programming  Code Snippet Library  The freebie code comes from the code snippet library. 代码来自cod ...

  2. iOS中的蓝牙

    iOS中的蓝牙 概述 iOS中提供了4个框架用于实现蓝牙连接 1.GameKit.framework(用法简单) 只能用于iOS设备之间的同个应用内连接,多用于游戏(eg.拳皇,棋牌类),从iOS7开 ...

  3. qt5.5版本的creator构建套件自动检测为警告

    原创,转载请注明http://www.cnblogs.com/dachen408/p/7226188.html 原因,安装qt在E盘,winsdksetup也在E盘 的原因,卸载winsdksetup ...

  4. C#斐波那契数列递归算法

    public static int Foo(int i)        {            if (i < 3)            {                return 1; ...

  5. 程序员容易忽略的SQL Server错误集锦

    1.大小写 大写T-SQL 语言的所有关键字都使用大写,规范要求. 2.使用“;” 使用“;”作为 Transact-SQL 语句终止符.虽然分号不是必需的,但使用它是一种好的习惯,对于合并操作MER ...

  6. uiviewcontroller顶级布局控制

    @available(iOS 7.0, *) open var edgesForExtendedLayout: UIRectEdge // Defaults to UIRectEdgeAll @ava ...

  7. formSelects-v4.js 基于Layui的多选解决方案

    https://hnzzmsf.github.io/example/example_v4.html

  8. 哈尔滨工程大学ACM预热赛 补题

    链接:https://ac.nowcoder.com/acm/contest/554/A来源:牛客网 小虎刚刚上了幼儿园,老师让他做一个家庭作业:首先画3个格子,第二行有2个格子,第三行有1个格子. ...

  9. 2. 区分散列的 undef 值, 和手动赋值 0 不一样。1. 使用exists函数,散列中有这个键(必须是keys %hash 有这结果),则返回真值,

    2. 123 my %vertical_alignment;    124 $vertical_alignment{"subscripting"} = 0;    125 unle ...

  10. 用PHP怎么删除某目录下指定的一个文件

    举个tp框架的例子 $User = M("message"); $a = $User->]['url']; unlink($url); $User->delete($i ...