servlet实现文件下载 以什么文件类型

Java EE复习题选择题(有答案)_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
Java EE复习题选择题(有答案)
上传于|0|0|文档简介
&&Java EE复习题选择题,是有答案的,正确的答案。
阅读已结束,如果下载本文需要使用0下载券
想免费下载更多文档?
定制HR最喜欢的简历
下载文档到电脑,查找使用更方便
还剩8页未读,继续阅读
定制HR最喜欢的简历
你可能喜欢java.lang.Error: 无法解析的编译问题:
无法解析类型 javax.servlet.http.HttpServletRequest。从必需的 .class 文件间接引用了它
无法解析类型 javax.servlet.http.HttpServletResponse。从必需的 .class 文件间接引用了它
无法解析类型 javax.servlet.http.HttpSession。从必需的 .class 文件间接引用了它
无法解析导入 javax.servlet.http.HttpServletRequest
无法解析导入 javax.servlet.http.HttpServletResponse
解决的方法:
是因为没有为项目导入服务器的运行环境;
具体的方法是右键项目--〉java 构建路径--〉添加库(A);选择一个tomcat版本
阅读(...) 评论()java基于servlet编写上传下载功能 类似文件服务器
java基于servlet编写上传下载功能 类似文件服务器
本人闲来无事,写了个servlet,实现上传下载功能。启动服务后,可以在一个局域网内当一个小小的文件服务器。&
一、准备工作
下载两个jar包:&
commons-fileupload-1.3.1.jar
commons-io-2.2.jar&
二、创建一个web工程
我的工程名叫:z-upload&
三、配置web.xml
&?xml version="1.0" encoding="UTF-8"?&
&web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="/xml/ns/javaee"
xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0"&
&display-name&z-upload&/display-name&
&servlet-name&UploadService&/servlet-name&
&servlet-class&com.syz.servlet.UploadService&/servlet-class&
&/servlet&
&servlet-mapping&
&servlet-name&UploadService&/servlet-name&
&url-pattern&/*&/url-pattern&
&/servlet-mapping&
&/web-app&
&从以上配置可以看出,我的servlet类是UploadService,匹配的url是/*,意思是匹配所有访问url。&
四、写servlet类
package com.syz.
import java.io.F
import java.io.FileInputS
import java.io.FileOutputS
import java.io.IOE
import java.io.InputS
import java.io.OutputS
import java.io.PrintW
import java.text.SimpleDateF
import java.util.D
import java.util.I
import java.util.L
import javax.servlet.ServletC
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import mons.fileupload.FileI
import mons.fileupload.FileUploadE
import mons.fileupload.ProgressL
import mons.fileupload.disk.DiskFileItemF
import mons.fileupload.servlet.ServletFileU
public class UploadService extends HttpServlet {
public static final String LIST = "/list";
public static final String FORM = "/form";
public static final String HANDLE = "/handle";
public static final String DOWNLOAD = "/download";
public static final String DELETE = "/delete";
public static final String UPLOAD_DIR = "/upload";
private static final long serialVersionUID = 2860765L;
public void execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("execute...");
System.out.println("------------begin---------------");
req.setCharacterEncoding("UTF-8");
String host = req.getRemoteHost();
System.out.println("host:" + host);
String uri = req.getRequestURI();
System.out.println("uri:" + uri);
ServletContext servletContext = this.getServletConfig()
.getServletContext();
// 上传文件的基本路径
String basePath = servletContext.getRealPath(UPLOAD_DIR);
// 上下文路径
String contextPath = servletContext.getContextPath();
System.out.println("contextPath:" + contextPath);
// 截取上下文之后的路径
String action = uri.substring(contextPath.length());
System.out.println("action:" + action);
// 依据action不同进行不同的处理
if (action.equals(FORM)) {
form(contextPath, resp);
else if (action.equals(HANDLE)) {
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
System.out.println("isMultipart:" + isMultipart);
if (!isMultipart) {
DiskFileItemFactory factory = new DiskFileItemFactory();
File repository = (File) servletContext
.getAttribute(ServletContext.TEMPDIR);
System.out.println("repository:" + repository.getAbsolutePath());
System.out.println("basePath:" + basePath);
factory.setSizeThreshold(1024 * 100);
factory.setRepository(repository);
ServletFileUpload upload = new ServletFileUpload(factory);
// 创建监听
ProgressListener progressListener = new ProgressListener() {
public void update(long pBytesRead, long pContentLength,
int pItems) {
System.out.println("当前文件大小:" + pContentLength + "\t已经处理:"
+ pBytesRead);
upload.setProgressListener(progressListener);
List&FileItem& items =
items = upload.parseRequest(req);
System.out.println("items size:" + items.size());
Iterator&FileItem& ite = items.iterator();
while(ite.hasNext()){
FileItem item = ite.next();
if(item.isFormField()){
// handle FormField
// handle file
String fieldName = item.getFieldName();
String fileName = item.getName();
fileName = fileName.substring(
fileName.lastIndexOf(File.separator) + 1);
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
System.out.println(fieldName + "\t" + fileName + "\t"
+ contentType + "\t" + isInMemory + "\t"
+ sizeInBytes);
File file = new File(
basePath + "/" + fileName + "_" + getSuffix());
// item.write(file);
InputStream in = item.getInputStream();
OutputStream out = new FileOutputStream(file);
byte[] b = new byte[1024];
int n = 0;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
out.flush();
in.close();
out.close();
// 处理完后重定向到文件列表页面
String href1 = contextPath + LIST;
resp.sendRedirect(href1);
catch (FileUploadException e) {
e.printStackTrace();
catch (Exception e) {
e.printStackTrace();
else if (action.equals(LIST)) {
list(contextPath, basePath, resp);
else if (action.equals(DOWNLOAD)) {
String id = req.getParameter("id");
System.out.println("id:" + id);
if (id == null) {
File file = new File(basePath);
File[] list = file.listFiles();
int len = list.
boolean flag =
for (int i = 0; i & i++) {
File f = list[i];
String fn = f.getName();
if (f.isFile() && fn.lastIndexOf("_") & -1) {
String fid = fn.substring(fn.lastIndexOf("_"));
if (id.equals(fid)) {
download(f, resp);
if (!flag) {
notfound(contextPath, resp);
else if (action.equals(DELETE)) {
String id = req.getParameter("id");
System.out.println("id:" + id);
if (id == null) {
File file = new File(basePath);
File[] list = file.listFiles();
int len = list.
boolean flag =
for (int i = 0; i & i++) {
File f = list[i];
String fn = f.getName();
if (f.isFile() && fn.lastIndexOf("_") & -1) {
String fid = fn.substring(fn.lastIndexOf("_"));
if (id.equals(fid)) {
f.delete();
if (flag) {
// 处理完后重定向到文件列表页面
String href1 = contextPath + LIST;
resp.sendRedirect(href1);
notfound(contextPath, resp);
show404(contextPath, resp);
System.out.println("------------end---------------");
private void show404(String contextPath, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/charset=utf-8");
PrintWriter out = resp.getWriter();
String href1 = contextPath + LIST;
out.write("&html&");
out.write("&head&&title&404&/title&&/thead&");
out.write("&body&");
out.write("&b&您所访问的页面不存在!&a href='" + href1 + "'&点击&/a&返回文件列表&/b&");
out.write("&/body&");
out.write("&/html&");
out.close();
private void form(String contextPath, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/charset=utf-8");
PrintWriter out = resp.getWriter();
String href1 = contextPath + LIST;
out.write("&html&");
out.write("&head&&title&form&/title&&/thead&");
out.write("&body&");
out.write("&b&&a href='" + href1 + "'&点击&/a&返回文件列表&/b&");
out.write(
"&form action='handle' method='post' enctype='multipart/form-data' style='margin-top:20'&");
out.write("&input name='file' type='file'/&&br&");
out.write("&input type='submit' value='上传'/&&br&");
out.write("&/form&");
out.write("&/body&");
out.write("&/html&");
out.close();
private void notfound(String contextPath, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/charset=utf-8");
PrintWriter out = resp.getWriter();
String href1 = contextPath + LIST;
out.write("&html&&body&&b&操作失败!文件不存在或文件已经被删除!&a href='" + href1
+ "'&点击&/a&返回文件列表&/b&&/body&&/html&");
out.close();
private void download(File f, HttpServletResponse resp)
throws IOException {
String fn = f.getName();
String fileName = fn.substring(0, fn.lastIndexOf("_"));
System.out.println("fileName:" + fileName);
resp.reset();
resp.setContentType("application/octet-stream");
String encodingFilename = new String(fileName.getBytes("GBK"),
"ISO8859-1");
System.out.println("encodingFilename:" + encodingFilename);
resp.setHeader("content-disposition",
"filename=" + encodingFilename);
InputStream in = new FileInputStream(f);
OutputStream out = resp.getOutputStream();
byte[] b = new byte[1024];
int n = 0;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
out.flush();
in.close();
out.close();
private void list(String contextPath, String basePath,
HttpServletResponse resp)
throws IOException {
String href_u = contextPath + FORM;
resp.setContentType("text/charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("&html&");
out.write("&head&&title&list&/title&&/thead&");
out.write("&body&");
out.write("&b&我要&a href='" + href_u + "'&上传&/a&&/b&&br&");
out.write(
"&table border='1' style='border-collapse:width:100%;margin-top:20'&");
out.write("&thead&");
out.write("&tr&");
out.write("&th&序号&/th&&th&文件名&/th&&th&操作&/th&");
out.write("&/tr&");
out.write("&/thead&");
out.write("&tbody&");
File file = new File(basePath);
File[] list = file.listFiles();
System.out
.println("basePath:" + basePath + "\tlist.size:" + list.length);
int len = list.
int no = 1;
for (int i = 0; i & i++) {
File f = list[i];
System.out.println(i + "\t" + f.getName());
String fn = f.getName();
if (f.isFile() && fn.lastIndexOf("_") & -1) {
String filename = fn.substring(0, fn.lastIndexOf("_"));
String id = fn.substring(fn.lastIndexOf("_"));
String href1 = contextPath + DOWNLOAD + "?id=" +
String href2 = contextPath + DELETE + "?id=" +
StringBuilder sb = new StringBuilder();
sb.append("&tr&");
sb.append("&td&");
sb.append(no++);
sb.append("&/td&");
sb.append("&td&");
sb.append(filename);
sb.append("&/td&");
sb.append("&td&");
sb.append("&a href='");
sb.append(href1);
sb.append("'&下载&/a& &a href='");
sb.append(href2);
sb.append("' onclick='return confirm(\"您确定要删除吗?\");'&删除&/a&");
sb.append("&/td&");
sb.append("&/tr&");
out.write(sb.toString());
out.write("&/tbody&");
out.write("&/table&");
out.write("&/body&");
out.write("&/html&");
out.close();
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doGet...");
execute(req, resp);
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doPost...");
execute(req, resp);
private String getSuffix() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String suffix = sdf.format(date);
其实UploadService类可以直接实现service方法,而不用实现doGet、doPost方法。
以上servlet我也不想多解释什么,自己看代码吧。
五、效果图
1.项目结构图
/*会匹配所有包括空字符,所以图片中的路径会匹配,在UploadService中的if判断中出现在else中,因为此时的action是空字符。
3.文件列表页面
4.上传表单页面
7.文件找不到,如果你点删除时,文件在服务器上已经不存在,那么会进入此页面
8.打包的源码工程和war包
其中z-upload是eclipse源码工程,z-upload.war是打好的war包
全工程就两个jar包,一个web.xml和一个servlet类,可以自己从文章中拷贝过去测试一下,如果是懒人,可以下载
http://download.csdn.net/detail/yunsyz/9569680,特别提醒,下载要1分哦。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持phpstudy。
Copyright & 2016 phpStudy

我要回帖

更多关于 servlet配置文件 的文章

 

随机推荐