纯jsp servlet 实现 upload file功能

本篇主要是简单的实现jsp servlet 的上传文件的功能,基于servlet 2.5。
[b]jar依赖:[/b]
commons-fileupload/commons-io/servlet-api(commons-fileupload 自动依赖common-io)
pom.xml文件的内容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.luchenghao.demo</groupId>
<artifactId>gridconfig</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
</properties>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

</dependencies>
</project>


[b]form 表单的内容[/b]:
要点: method必须是post方法,get是不支持文件上传的。
enctype 属性值为:multipart/form-data。
action 的名字可以取了humanable的值就好了。
input的type要设为file,以支持文件类型。
代码如下:

<!DOCTYPE title PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Uploading Form</title>
</head>
<h3>File Upload:</h3>
Select a file to upload: <br/>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="Submit" value="Upload"/>
</form>
</html>



为了能把上传的文件保存起来,我们配置一个保存的路径c:\temp\data, 这个路径必须是真是存在,如果不存在就手动去创建该目录(in web.xml)如下:

<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:\temp\data\
</param-value>
</context-param>


[b]整个web.xml如下[/b]:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>
c:\temp\data\
</param-value>
</context-param>

<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.statestreetgx.fcm.core.controller.UploadController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
</web-app>





后台的servlet代码如下:

package com.statestreetgx.fcm.core.controller;

import java.io.File;
import java.util.Iterator;
import java.util.List;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
*
* @author a574539
*/
public class UploadController extends HttpServlet {

/**
* serialVersionUID
*/
private static final long serialVersionUID = -3218211616591116540L;
private boolean isMultipart;
private String filePath;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private File file;

public void init() {
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
if (!isMultipart) {
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>");
return;
}
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>Servlet 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();
String contentType = fi.getContentType();
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: " + fileName + "<br>");
}
}
out.println("</body>");
out.println("</html>");
} catch (Exception ex) {
System.out.println(ex);
}
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {

throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
}

// @RequestMapping(value = "upload")
// @ResponseBody
// public void upload() {
// System.out.println("hello");
// }
}


参考链接:[url]http://www.tutorialspoint.com/servlets/servlets-file-uploading.htm[/url]

--EOF--
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值