代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Java
】
实现文件上传和下载功能
作者:
xychenqiang
/ 发布于
2015/8/10
/
591
FileUploadServlet.java package upload; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * 上传文件 */ import java.io.PrintWriter; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import exception.FileSizeException; import exception.FileTypeException; import util.WebUtil; public class FileUploadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //通知浏览器以UTF-8的方式来解码 request.setCharacterEncoding("UTF-8"); //创建上传文件的工厂 DiskFileItemFactory factory = new DiskFileItemFactory(); //设置上传文件的临时缓存区为100k factory.setSizeThreshold(100*1024); //定位临时目录的路径,这里的/表示当前Web应用的根目录 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); //设置上传文件超过100K的临时目录存放点 factory.setRepository(new File(tempPath)); //创建上传文件对象(核心) ServletFileUpload fileUpload = new ServletFileUpload(factory); //判断客户端是否已RCF协议的方式上传 if(fileUpload.isMultipartContent(request)){ //解析request对象中的表单字段 List<FileItem> fileItemList = fileUpload.parseRequest(request); //迭代 for(FileItem fileItem : fileItemList){ //如果是普通字段 if(fileItem.isFormField()){ String fileName = fileItem.getFieldName(); String fileNameValue = fileItem.getString("UTF-8"); //显示 System.out.println(fileName + ":" + fileNameValue); }else if(!fileItem.isFormField()){ //获取上传文件的名字 String filename = fileItem.getName(); //获得UuidFileName String uuidFileName = WebUtil.makeUuidFileName(filename); System.out.println(uuidFileName); //定位上传文件的存放的目录 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); //获取上传文件存放的子目录 String subUploadPath = WebUtil.subUploadPath(uploadPath,uuidFileName); //获取上传文件的大小 long size = fileItem.getSize(); //如果上传文件超过200K if(size>200*1024){ //人工抛出异常 throw new FileSizeException(); } //获取上传文件的类型 String contentType = fileItem.getContentType(); //如果上传的文件类型不是JPG格式 if(!"image/jpeg".equals(contentType)){ //人工抛出异常 throw new FileTypeException(); } //调用工具类的方法writeToFiel WebUtil.writeToFile(fileItem, subUploadPath, uuidFileName); /*//获取上传文件输入流 InputStream is = fileItem.getInputStream(); //定位文件输出流 OutputStream os = new FileOutputStream(new File(uploadPath + "/" + name)); //将上传文件写入指定的目录下 byte[] buf = new byte[2048]; int len = 0; while((len = is.read(buf))>0){ os.write(buf,0,len); } os.close(); is.close(); */ //把临时文件删除 fileItem.delete(); } } request.setAttribute("message", "<font style = 'font-size:111ps;color:red'>上传成功</font>"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response); }else{ request.setAttribute("message", "<font style = 'font-size:111px;color:red'>上传文件必须采用RFC协议指定的格式</font>"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response); } } //上传文件的大小不能超过200K catch (FileSizeException e) { e.printStackTrace(); request.setAttribute("message", "<font style = 'font-size:111ps;color:red'>上传文件失败!上传文件不能超过200K</font>"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response); } //上传文件必须为图片类型 catch (FileTypeException e) { e.printStackTrace(); request.setAttribute("message", "<font style = 'font-size:111ps;color:red'>上传文件失败!上传文件必须是图片类型的</font>"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); request.setAttribute("message", "<font style = 'font-size:111ps;color:red'>解析上传表单出错</font>"); request.getRequestDispatcher("/WEB-INF/message.jsp").forward(request, response); } } } <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'list.jsp' starting 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"> </head> <body> <table border = "2" align = "center" width = "40%"> <tr> <th>文件</th> <th>操作</th> </tr> <c:forEach var = "entry" items = "${requestScope.MAP}"> <tr> <td>${entry.value}</td> <td> <c:url var = "myURL" value = "/fileDownload"> <c:param name = "uuidFileName" value = "${entry.key}" /> </c:url> <a style = "text-decoration:none" href = "${myURL}">下载</a> </td> </tr> </c:forEach> </table> </body> </html>
试试其它关键字
文件上传
同语言下
.
List 切割成几份 工具类
.
一行一行读取txt的内容
.
Java PDF转换成图片并输出给前台展示
.
java 多线程框架
.
double类型如果小数点后为零则显示整数否则保留两位小
.
将图片转换为Base64字符串公共类抽取
.
sqlParser 处理SQL(增删改查) 替换schema 用于多租户
.
JAVA 月份中的第几周处理 1-7属于第一周 依次类推 29-
.
java计算两个经纬度之间的距离
.
输入时间参数计算年龄
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
xychenqiang
贡献的其它代码
(
1
)
.
实现文件上传和下载功能
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3