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.输出流,写出文件数据到服务器硬盘 ...
随机推荐
- QT文件夹定位(网友提供)
#ifndef FOLDERFINDER_H #define FOLDERFINDER_H#include <QDir>class FolderFinder{public: QStr ...
- 基于google earth engine 云计算平台的全国水体变化研究
第一个博客密码忘记了,今天才来开通第二个博客,时间已经过去两年了,三年的硕士生涯,真的是感慨良多,最有收获的一段时光,莫过于在实验室一个人敲着代码了,研三来得到中科院深圳先进院,在这里开始了新的研究生 ...
- [Cycle.js] Hello World in Cycle.js
Now you should have a good idea what Cycle.run does, and what the DOM Driver is. In this lesson, we ...
- 2013年全球ERP市场格局(Gartner)
Gartner于5月5日公布了全球ERP市场的分析报告,报告称全球ERP软件销售额2013年整体增长了3.8%(从2012年$244亿美元到2013年$258亿美元),全球前五位ERP厂商座次例如以下 ...
- Android内存泄漏监测(MAT)及解决办法
http://ttlnews.blogspot.com/2010/01/attacking-memory-problems-on-android.html 这篇文章是2010年1月份写的,其中有些已经 ...
- [HeadFirst-HTMLCSS入门][第十章div,span]
新元素 <div>逻辑容器 能进行分组,等于用一个大的盒子进行包装 <span> 内联字符的逻辑分组 text-align 改变所有内联元素位置. 属性 center 居中 行 ...
- table-cell完成左侧定宽,右侧定宽及左右定宽等布局
使用table-cell完成以下几种布局(ie8及以上兼容) 1.左侧定宽-右侧自适应 .left{ width: 300px; height: 500px; border: 1px solid; f ...
- AFNetWorking 关于manager.requestSerializer.timeoutInterval 不起作用的问题
之前一直遇到关于AFNetWorking请求时间设置了但是不起作用的情况,现用如下方式设置AF的超市时间即可. [manager.requestSerializer willChangeValueFo ...
- C# 广播TS流精确计时发送
广播传输相关的项目,需求是UDP发送TS到IP/ASI网关,网关经过ASI输出到激励器,再由激励器通过射频天线输出,接收端为终端机顶盒. 因为以前没有怎么接触过广播相关的东西,一开始认为用C#写个UD ...
- Linux安装系统注意事项及系统初始化
Linux安装系统注意事项 1.分区 学习用途: /boot:200M /swap :内存的1到2倍 /:根据需要分配大小,比如虚拟机下总空间是15G,那么可以分配8——10G跟/分区,如果是生产 ...