文件上传
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的使用案例的更多相关文章

  1. Email系列(QQ邮箱 + 含附件的邮箱案例 + 项目实战)

    平台之大势何人能挡? 带着你的Net飞奔吧! http://www.cnblogs.com/dunitian/p/4822808.html 邮箱系列:https://github.com/duniti ...

  2. extjs插件开发上传下载文件简单案例

    前台,extjs,框架,mybatis,spring,springMVC,简单的文件上传下载案例. 必要的jar包,commons-fileupload-1.3.1.jar,commons-io-2. ...

  3. 文件上传组件FileUpload 以及邮箱搭建JavaMail

     文件上传与下载 1.1 文件上传 案例: 注册表单/保存商品等相关模块! --à 注册选择头像 / 商品图片 (数据库:存储图片路径 / 图片保存到服务器中指定的目录) 文件上传,要点: 前台: 1 ...

  4. SpringMvc的Url映射和传参案例(转)

    Springmvc的基本使用,包括url映射.参数映射.页面跳转.ajax和文件上传 以前学习的时候写的代码案例,今天整理笔记的时候找到了,很久没有来园子了,发上来当个在线笔记用吧,免的时间长了又忘了 ...

  5. SpringMvc的Url映射和传参案例

    Springmvc的基本使用,包括url映射.参数映射.页面跳转.ajax和文件上传 以前学习的时候写的代码案例,今天整理笔记的时候找到了,很久没有来园子了,发上来当个在线笔记用吧,免的时间长了又忘了 ...

  6. springmvc文件上传下载简单实现案例(ssm框架使用)

    springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...

  7. 《JavaWeb从入门到改行》fileupload,没毛病

    目录: »  fileupload API >  文件上传的要求 >  fileupload组件 »  上传细节的代码演示 »  项目案例-上传头像并显示 fileupload API 文 ...

  8. 微信小程序语音同步智能识别的实现案例

    目录 一.背景 二.同声传译插件介绍 1. 微信小程序后台添加插件 2. 微信小程序启用插件 三.语音同步转换的前端实现 1.界面UI与操作 2.代码实现 四.后端SpringBoot实现语音文件上传 ...

  9. Java实现一个简单的文件上传案例

    Java实现一个简单的文件上传案例 实现流程: 1.客户端从硬盘读取文件数据到程序中 2.客户端输出流,写出文件到服务端 3.服务端输出流,读取文件数据到服务端中 4.输出流,写出文件数据到服务器硬盘 ...

随机推荐

  1. handsontable常规配置的中文API

    常规配置: 1.固定行列位置 fixedRowsTop:行数 //固定顶部多少行不能垂直滚动 fixedColumnsLeft:列数 //固定左侧多少列不能水平滚动 2.拖拽行头或列头改变行或列的大小 ...

  2. struts——拦截器

    什么是拦截器 拦截器(Interceptor)是Struts 2的一个强有力的工具,有许多功能都是构建于它之上,如国际化(前两篇博客介绍过).转换器,校验等. 拦截器是动态拦截Action调用的对象. ...

  3. 用Visual Studio2010 编译 C++文件"hello world”

    本周开始学习C++语言,用Visual Studio 2010做编译器,发现站内还没有基础的关于用VS2010编译程序的教材.而且自己在网上寻找时候,教程难找,而且大都不详细.故写一个关于这方面的教程 ...

  4. 自增运算a++和++b(1)

    #include<reg52.h> #define uint unsigned int #define uchar unsigned char uchar code f[]={0x3f,0 ...

  5. 阻止IOS自动识别页面上的电话号码、email地址

    之前写页面的时候碰到一个很恶心的情况,在6P上数字自动变色,后来找了一些资料: 在iOS的浏览器上,他们有时候会有一些“自作聪明”,自动把页面上的一串数字识别成电话号码,这样用户不小心点击这串数字,就 ...

  6. SQLserver 连接+开窗函数+视图+事务

    今天学习SQLserver 连接以及开窗函数..加油! 1.复习:查询(检索)->筛选列->筛选行:distinct top where 运算符与关键字:比较运算符,逻辑运算符,betwe ...

  7. T-SQL 函数概述

    T-SQL函数的类别和描述: 函数类别 作用 聚合函数 返回一个标量值,表示在某个值域上的聚合,应用于特定的聚合选择或者汇总 配置变量 返回SQL Server执行环境的信息.这些信息可用于给对象编程 ...

  8. 8051、ARM、AVR

    arm精简指令集.可以安装嵌入式操作系统 8051复杂指令集 avr没落了

  9. Django auth 登陆后页面跳转至/account/profile,修改跳转至其他页面

    这几天在学习django,django功能很强大,自带的auth,基本可以满足用户注册登陆登出,简单的用户注册登陆系统使用django auth足矣.当然也不是拿来就能用的,需要自己写登陆页面的模板, ...

  10. 异常处理与调试 - 零基础入门学习Delphi50

    异常处理与调试 让编程改变世界 Change the world by program 异常处理与调试 在应用程序开发中如何检测.处理程序的运行错误是一个很重要的问题. 有些错误是无法控制的. 如何处 ...