FileUpload的使用案例
文件上传
1、www.apache.org下载commons fileupload 和 commons io
2、创建jsp并附上如下代码
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%> <%
String strId = request.getParameter("id");
int id = 0;
if(strId == null && strId.trim().equals("")){
out.println("你选择的商品有错!");
return;
}
id = Integer.parseInt(strId);
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title> <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 action="../FileUpload" method="post" enctype="multipart/form-data" name="form1">
<input type="hidden" name="id" value="<%=id %>">
<input type="file" name="file">
<input type="submit" name="Submit" value="upload">
</form>
<br>
<br>
<form name="uploadform" method="POST" action="./servlet/FileUpload" ENCTYPE="multipart/form-data"> <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF"> <tr><td width="100%" colspan="2"> 文件1:<input name="x" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件2:<input name="y" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件3:<input name="z" size="40" type="file"> </td></tr> </table> <br/><br/> <table> <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr> </table> </form> </body>
</html>
3、直接在项目下创建servlet并附上如下代码
package com.cuijun.shopping.servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory; public class FileUpload extends HttpServlet { String uploadPath = ""; @Override
public void init(ServletConfig config) throws ServletException {
uploadPath = config.getInitParameter("uploadPath");
} int id = -1; public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html; charset=GB18030");
PrintWriter out = res.getWriter();
System.out.println(req.getContentLength());
System.out.println(req.getContentType());
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(new File("d:\\temp\\")); ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000);
try {
List fileItems = upload.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator(); // 正则匹配,过滤路径取文件名
String regExp = ".+\\\\(.+)$"; // 过滤掉的文件类型
String[] errorType = { ".exe", ".com", ".cgi", ".asp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (item.isFormField()){
if(item.getFieldName().equals("id")){
id = Integer.parseInt(item.getString());
}
}
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++) {
if (m.group(1).endsWith(errorType[temp])) {
throw new IOException(name + ": wrong type");
}
}
try { // 保存上传的文件到指定的目录 // 在下文中上传文件至数据库时,将对这里改写
//item.write(new File("d:\\" + m.group(1)));
item.write(new File(uploadPath + id + ".jpg")); out.print(name + " " + size + "<br>");
} catch (Exception e) {
out.println(e);
} } else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
out.println(e);
} catch (FileUploadException e) {
out.println(e);
} // 保存上传的文件到指定的目录 // 在下文中上传文件至数据库时,将对这里改写 } }
4、注意代码中的路径问题。千万小心。
1、路径中\\代表\。不要写成//。
2、路径后面不要忘记添加\\。
5、接受id。
1、先定义int id = -1;
2、判断接受的域是正常域if (item.isFormField()){
if(item.getFieldName().equals("id")){
id = Integer.parse(item.getString());
}
}
3、把上传的文件写到内存item.write(new File(uploadPath + id + ".jpg"));
6、修改WEB-INF下的配置文件
1、添加<init-param>
<param-name>uploadPath</param-name>
<param-value>D:\\web\\Shopping\\WebContent\\image\\product\\</param-value>
</init-param>
2、在servlet中重写init方法String uploadPath = ""; @Override
public void init(ServletConfig config) throws ServletException {
uploadPath = config.getInitParameter("uploadPath");
}
7、Over!
FileUpload的使用案例的更多相关文章
- Email系列(QQ邮箱 + 含附件的邮箱案例 + 项目实战)
平台之大势何人能挡? 带着你的Net飞奔吧! http://www.cnblogs.com/dunitian/p/4822808.html 邮箱系列:https://github.com/duniti ...
- extjs插件开发上传下载文件简单案例
前台,extjs,框架,mybatis,spring,springMVC,简单的文件上传下载案例. 必要的jar包,commons-fileupload-1.3.1.jar,commons-io-2. ...
- 文件上传组件FileUpload 以及邮箱搭建JavaMail
文件上传与下载 1.1 文件上传 案例: 注册表单/保存商品等相关模块! --à 注册选择头像 / 商品图片 (数据库:存储图片路径 / 图片保存到服务器中指定的目录) 文件上传,要点: 前台: 1 ...
- SpringMvc的Url映射和传参案例(转)
Springmvc的基本使用,包括url映射.参数映射.页面跳转.ajax和文件上传 以前学习的时候写的代码案例,今天整理笔记的时候找到了,很久没有来园子了,发上来当个在线笔记用吧,免的时间长了又忘了 ...
- SpringMvc的Url映射和传参案例
Springmvc的基本使用,包括url映射.参数映射.页面跳转.ajax和文件上传 以前学习的时候写的代码案例,今天整理笔记的时候找到了,很久没有来园子了,发上来当个在线笔记用吧,免的时间长了又忘了 ...
- springmvc文件上传下载简单实现案例(ssm框架使用)
springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...
- 《JavaWeb从入门到改行》fileupload,没毛病
目录: » fileupload API > 文件上传的要求 > fileupload组件 » 上传细节的代码演示 » 项目案例-上传头像并显示 fileupload API 文 ...
- 微信小程序语音同步智能识别的实现案例
目录 一.背景 二.同声传译插件介绍 1. 微信小程序后台添加插件 2. 微信小程序启用插件 三.语音同步转换的前端实现 1.界面UI与操作 2.代码实现 四.后端SpringBoot实现语音文件上传 ...
- Java实现一个简单的文件上传案例
Java实现一个简单的文件上传案例 实现流程: 1.客户端从硬盘读取文件数据到程序中 2.客户端输出流,写出文件到服务端 3.服务端输出流,读取文件数据到服务端中 4.输出流,写出文件数据到服务器硬盘 ...
随机推荐
- ios实现程序切入后台,实现后台任务
首先,iOS 会再持续切入后台,给我们5秒钟的时间去处理相关数据,5秒后,程序不会再执行任何代码,处于挂起状态. // 项目需求,按下Home切换后台后向服务器传一些数据,废话不多说,直接上代码 /* ...
- All X(思维)
All X Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Subm ...
- C# CheckedListBox控件的使用方法
1. 加入项 checkedListBox1.Items.Add("蓝色"); checkedListBox1.Items.Add("红色"); checked ...
- ios 自己定义导航栏和切割线
自己定义导航栏: // CustomNaviBarView.h #import <UIKit/UIKit.h> @interface CustomNaviBarView : UIView ...
- CentOS6.5 --安装orale 11g(下)
(7) 建立Oracle系统用户和安装目录 创建一个主组oinstall和一个副组dba.命令如下: groupadd oinstall groupadd dba 创建oracle安装文件 m ...
- 代码先行-log4Net初体验
1.安装 从http://logging.apache.org/log4net/download_log4net.cgi下载编译好的log4Net包并解压. 找到 bin\net\4.0\releas ...
- ckplayer,超酷网页播放器,用于集成在网站中的播放器
自己在工作中做了一个教学网站,点击左边课程,右边播放视频,经过源代码分析,用的就是这个播放器 网址:http://www.ckplayer.com/ 具体使用播放器网站上说的比较明白 div id=& ...
- iOS之本地推送(前台模式与后台模式)
#import "AppDelegate.h" #import "GlobalDefine.h" @interface AppDelegate () @end ...
- struts2 实现过程和xml配置
实现过程: 当Web容器收到 请求(HttpServletRequest)它将请求传递给一个标准的的过滤链包括 (ActionContextCleanUp)过滤器,然后经过Other filters( ...
- 关于Struts2的类型转换详解
详细出处参考:http://www.jb51.net/article/35465.htm 一.类型转换的意义 对于一个智能的MVC框架而言,不可避免的需要实现类型转换.因为B/S(浏览器/服务器)结构 ...