上传的文件一般保存在运行项目中,把可访问的地址保存在数据库中

servlet上传文件需要的jar包:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

<title>This is my JSP page</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>
<!--

要上传文件的时候 一定要将 form 设置为 post 还要将 form 的 enctype设置为 multipart/form-data

-->

<form action="uploadController" method="post" enctype="multipart/form-data">
文件:<input type="file" name="testfile" ><br>
描述:<input type="text" name="description" ><br>
<input type="submit" value="上传" />
</form>
</body>
</html>

 

 

 

UploadController.java

package com.huawei.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

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;

/**
* Servlet implementation class UploadController
*/
public class UploadController extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public UploadController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");

/*System.out.println(request.getParameter("description"));

InputStream in = request.getInputStream();
OutputStream out = new FileOutputStream(new File("F:/upload.txt"));

byte []bytes = new byte[1024*8];
int len = 0;

while((len = in.read(bytes))!=-1){
out.write(bytes, 0, len);
}
out.flush();
out.close();
in.close();*/


//使用FileUpload文件上传插件的步骤
//第一步 解析 测试 请求是否为 文件上传的请求

boolean flag = ServletFileUpload.isMultipartContent(request);
if(flag){
//解析请求

//基于文件系统创建文件选项的工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//得到 application 用户得到缓存的临时目录
ServletContext context = this.getServletContext();
//得到JVM自带的临时目录 不需要由我们自己去创建
File repository = (File)context.getAttribute("javax.servlet.context.tempdir");
//将仓库和工厂建立联系
factory.setRepository(repository);
//创建一个 ServletFileUpload 的实例
ServletFileUpload upload = new ServletFileUpload(factory);

try {
//解析request 得到 表单域
List<FileItem> items = upload.parseRequest(request);
//遍历 表单域
for(FileItem item:items){
//判断是否为普通表单域 如果不是 则为文件
if(item.isFormField()){
//获取字段在form表单中的名字
System.out.println(item.getFieldName());
//获取名字 用于文件
System.out.println(item.getName());
//获取数据的大小
System.out.println(item.getSize());
//获取该表单域的值
System.out.println(item.getString());
//获取header 不常用
System.out.println(item.getHeaders());
//获取值的类型 用于文件
System.out.println(item.getContentType());
}else{
//item.write(new File("F:/"+item.getName()));
String path = context.getRealPath("/");
System.out.println(path);
item.write(new File(path+"/"+item.getName()));
}
}

} catch (Exception e) {
e.printStackTrace();
}

}

}

}

 

 

 

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>TestUpload</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>UploadController</display-name>
<servlet-name>UploadController</servlet-name>
<servlet-class>com.huawei.upload.UploadController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadController</servlet-name>
<url-pattern>/uploadController</url-pattern>
</servlet-mapping>
</web-app>