表单里有上传文件
url:http://wanglizhuang.javaeye.com/blog/466524
文章分类:Web前端 关键字: 上传文件和获取表单值
- 在servlet里的代码如下:
在servlet里的代码如下:
- String[] string = { "title", "type", "content"};//表单里其他内容的name
- String filename = FileSave.save(request, response, string); // 保存文件获取保存的文件名称
- map = FileSave.map;//获取值
String[] string = { "title", "type", "content"};//表单里其他内容的name
String filename = FileSave.save(request, response, string); // 保存文件获取保存的文件名称
map = FileSave.map;//获取值
下面是公共类:
- package cn.com.crystalnet.common;
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- 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.FileUploadBase.SizeLimitExceededException;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- /**
- * title:处理文件上传
- * @author 王立壮
- *
- */
- public class FileSave {
- public static Map map = null;
- public static String save(HttpServletRequest request, HttpServletResponse response,String[] paramName) {
- String u_name = null;
- map = new HashMap();
- final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
- // 允许上传的文件格式的列表
- final String[] allowedExt = new String[] { "gif","jpg","png","word","excel","txt","zip","ppt","pdf" };
- response.setContentType("text/html");
- // 设置字符编码为UTF-8, 这样支持汉字显示
- response.setCharacterEncoding("UTF-8");
- // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
- DiskFileItemFactory dfif = new DiskFileItemFactory();
- dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
- dfif.setRepository(new File(request.getRealPath("/")
- + "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
- // 用以上工厂实例化上传组件
- ServletFileUpload sfu = new ServletFileUpload(dfif);
- // 设置最大上传尺寸
- sfu.setSizeMax(MAX_SIZE);
- PrintWriter out = null;
- try {
- out = response.getWriter();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- // 从request得到 所有 上传域的列表
- List fileList = null;
- try {
- fileList = sfu.parseRequest(request);
- if (fileList != null) {
- for (Iterator itr = fileList.iterator(); itr.hasNext();) {
- FileItem fileItem = (FileItem) itr.next();
- for (int i = 0; i < paramName.length; i++) {
- if (fileItem.getFieldName().equalsIgnoreCase(
- paramName[i])) {
- map.put(fileItem.getFieldName(), new String(fileItem.getString().getBytes("ISO8859-1"),"UTF-8"));// 中文转码
- }
- }
- }
- }
- System.out.println(fileList.size());
- } catch (FileUploadException e) {// 处理文件尺寸过大异常
- if (e instanceof SizeLimitExceededException) {
- out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />");
- out.println("<a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
- }
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- // 没有文件上传
- if (fileList == null || fileList.size() == 0) {
- out.println("请选择上传文件<p />");
- out.println("<a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
- }
- // 得到所有上传的文件
- Iterator fileItr = fileList.iterator();
- // 循环处理所有文件
- while (fileItr.hasNext()) {
- FileItem fileItem = null;
- String path = null;
- long size = 0;
- // 得到当前文件
- fileItem = (FileItem) fileItr.next();
- // 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
- if (fileItem == null || fileItem.isFormField()) {
- continue;
- }
- // 得到文件的完整路径
- path = fileItem.getName();
- // 得到文件的大小
- size = fileItem.getSize();
- if ("".equals(path) || size == 0) {
- out.println("请选择上传文件<p />");
- out.println("<a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
- break;
- }
- // 得到去除路径的文件名
- String t_name = path.substring(path.lastIndexOf("//") + 1);
- // 得到文件的扩展名(无扩展名时将得到全名)
- String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
- // 拒绝接受规定文件格式之外的文件类型
- int allowFlag = 0;
- int allowedExtCount = allowedExt.length;
- for (; allowFlag < allowedExtCount; allowFlag++) {
- if (allowedExt[allowFlag].equals(t_ext))
- break;
- }
- if (allowFlag == allowedExtCount) {
- out.println("请上传以下类型的文件<p />");
- for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
- out.println("*." + allowedExt[allowFlag]
- + " ");
- out
- .println("<p /><a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
- }
- long now = System.currentTimeMillis();
- // 根据系统时间生成上传后保存的文件名
- String prefix = String.valueOf(now);
- // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
- u_name = request.getRealPath("/") + "Back//mailUpload//"
- + prefix + "." + t_ext;
- try {
- // 保存文件
- fileItem.write(new File(u_name));
- u_name = "mailUpload/"+ prefix + "." + t_ext;
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return u_name;
- }
- }
package cn.com.crystalnet.common;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* title:处理文件上传
* @author 王立壮
*
*/
public class FileSave {
public static Map map = null;
public static String save(HttpServletRequest request, HttpServletResponse response,String[] paramName) {
String u_name = null;
map = new HashMap();
final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
// 允许上传的文件格式的列表
final String[] allowedExt = new String[] { "gif","jpg","png","word","excel","txt","zip","ppt","pdf" };
response.setContentType("text/html");
// 设置字符编码为UTF-8, 这样支持汉字显示
response.setCharacterEncoding("UTF-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setRepository(new File(request.getRealPath("/")
+ "ImagesUploadTemp"));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 从request得到 所有 上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
if (fileList != null) {
for (Iterator itr = fileList.iterator(); itr.hasNext();) {
FileItem fileItem = (FileItem) itr.next();
for (int i = 0; i < paramName.length; i++) {
if (fileItem.getFieldName().equalsIgnoreCase(
paramName[i])) {
map.put(fileItem.getFieldName(), new String(fileItem.getString().getBytes("ISO8859-1"),"UTF-8"));// 中文转码
}
}
}
}
System.out.println(fileList.size());
} catch (FileUploadException e) {// 处理文件尺寸过大异常
if (e instanceof SizeLimitExceededException) {
out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />");
out.println("<a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
}
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 没有文件上传
if (fileList == null || fileList.size() == 0) {
out.println("请选择上传文件<p />");
out.println("<a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0) {
out.println("请选择上传文件<p />");
out.println("<a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
break;
}
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("//") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowedExt.length;
for (; allowFlag < allowedExtCount; allowFlag++) {
if (allowedExt[allowFlag].equals(t_ext))
break;
}
if (allowFlag == allowedExtCount) {
out.println("请上传以下类型的文件<p />");
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
out.println("*." + allowedExt[allowFlag]
+ " ");
out
.println("<p /><a href=/"UserCenter.jsp/" target=/"_top/">返回</a>");
}
long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String prefix = String.valueOf(now);
// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
u_name = request.getRealPath("/") + "Back//mailUpload//"
+ prefix + "." + t_ext;
try {
// 保存文件
fileItem.write(new File(u_name));
u_name = "mailUpload/"+ prefix + "." + t_ext;
} catch (Exception e) {
e.printStackTrace();
}
}
return u_name;
}
}
==========================================================
jsp文件上传
url:http://myrl1023.javaeye.com/blog/265398
选把上传文件的插件cos下下来;
upload.html
upload.jsp
upload.html
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>文件上传前台控制检测程序 v0.6</title>
- <style>
- body,td{font-size:12px;}
- </style>
- <script language=javascript>
- var ImgObj=new Image(); //建立一个图像对象
- var AllImgExt=".jpg|.jpeg|.gif|.bmp|.png|"//全部图片格式类型
- var FileObj,ImgFileSize,ImgWidth,ImgHeight,FileExt,ErrMsg,FileMsg,HasCheked,IsImg//全局变量图片相关属性
- //以下为限制变量
- var AllowExt=".jpg|.gif|.doc|.txt|" //允许上传的文件类型 ?为无限制 每个扩展名后边要加一个"|" 小写字母表示
- //var AllowExt=0
- var AllowImgFileSize=70; //允许上传图片文件的大小 0为无限制 单位:KB
- var AllowImgWidth=500; //允许上传的图片的宽度 ?为无限制 单位:px(像素)
- var AllowImgHeight=500; //允许上传的图片的高度 ?为无限制 单位:px(像素)
- HasChecked=false;
- function CheckProperty(obj) //检测图像属性
- {
- FileObj=obj;
- if(ErrMsg!="") //检测是否为正确的图像文件 返回出错信息并重置
- {
- ShowMsg(ErrMsg,false);
- return false; //返回
- }
- if(ImgObj.readyState!="complete") //如果图像是未加载完成进行循环检测
- {
- setTimeout("CheckProperty(FileObj)",500);
- return false;
- }
- ImgFileSize=Math.round(ImgObj.fileSize/1024*100)/100;//取得图片文件的大小
- ImgWidth=ImgObj.width //取得图片的宽度
- ImgHeight=ImgObj.height; //取得图片的高度
- FileMsg="/n图片大小:"+ImgWidth+"*"+ImgHeight+"px";
- FileMsg=FileMsg+"/n图片文件大小:"+ImgFileSize+"Kb";
- FileMsg=FileMsg+"/n图片文件扩展名:"+FileExt;
- if(AllowImgWidth!=0&&AllowImgWidth<ImgWidth)
- ErrMsg=ErrMsg+"/n图片宽度超过限制。请上传宽度小于"+AllowImgWidth+"px的文件,当前图片宽度为"+ImgWidth+"px";
- if(AllowImgHeight!=0&&AllowImgHeight<ImgHeight)
- ErrMsg=ErrMsg+"/n图片高度超过限制。请上传高度小于"+AllowImgHeight+"px的文件,当前图片高度为"+ImgHeight+"px";
- if(AllowImgFileSize!=0&&AllowImgFileSize<ImgFileSize)
- ErrMsg=ErrMsg+"/n图片文件大小超过限制。请上传小于"+AllowImgFileSize+"KB的文件,当前文件大小为"+ImgFileSize+"KB";
- if(ErrMsg!="")
- ShowMsg(ErrMsg,false);
- else
- ShowMsg(FileMsg,true);
- }
- ImgObj.onerror=function(){ErrMsg='/n图片格式不正确或者图片已损坏!'}
- function ShowMsg(msg,tf) //显示提示信息 tf=true 显示文件信息 tf=false 显示错误信息 msg-信息内容
- {
- msg=msg.replace("/n","<li>");
- msg=msg.replace(//n/gi,"<li>");
- if(!tf)
- {
- document.all.UploadButton.disabled=true;
- FileObj.outerHTML=FileObj.outerHTML;
- MsgList.innerHTML=msg;
- HasChecked=false;
- }
- else
- {
- document.all.UploadButton.disabled=false;
- if(IsImg)
- PreviewImg.innerHTML="<img src='"+ImgObj.src+"' width='60' height='60'>"
- else
- PreviewImg.innerHTML="非图片文件";
- MsgList.innerHTML=msg;
- HasChecked=true;
- }
- }
- function CheckExt(obj)
- {
- ErrMsg="";
- FileMsg="";
- FileObj=obj;
- IsImg=false;
- HasChecked=false;
- PreviewImg.innerHTML="预览区";
- if(obj.value=="")return false;
- MsgList.innerHTML="文件信息处理中...";
- document.all.UploadButton.disabled=true;
- FileExt=obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();
- if(AllowExt!=0&&AllowExt.indexOf(FileExt+"|")==-1) //判断文件类型是否允许上传
- {
- ErrMsg="/n该文件类型不允许上传。请上传 "+AllowExt+" 类型的文件,当前文件类型为"+FileExt;
- ShowMsg(ErrMsg,false);
- return false;
- }
- if(AllImgExt.indexOf(FileExt+"|")!=-1) //如果图片文件,则进行图片信息处理
- {
- IsImg=true;
- ImgObj.src=obj.value;
- CheckProperty(obj);
- return false;
- }
- else
- {
- FileMsg="/n文件扩展名:"+FileExt;
- ShowMsg(FileMsg,true);
- }
- }
- function SwitchUpType(tf)
- {
- if(tf)
- str='<input type="file" name="file1" onchange="CheckExt(this)" style="width:180px;">'
- else
- str='<input type="text" name="file1" onblur="CheckExt(this)" style="width:180px;">'
- document.all.file1.outerHTML=str;
- document.all.UploadButton.disabled=true;
- MsgList.innerHTML="";
- }
- </script>
- </head>
- <body>
- <form enctype="multipart/form-data" method="POST" action="./upload.jsp?folderName=uploadImage&relativePath=../../" onsubmit="return HasChecked;">
- <fieldset style="width: 400px; height: 60;padding:2px;">
- <legend><font color="#FF0000">图片来源</font></legend>
- <input type="radio" name="radio1" checked onclick="SwitchUpType(true);">本地<input type="radio" name="radio1" onclick="SwitchUpType(false);">远程:<input type="file" name="file1" onchange="CheckExt(this)" style="width:180px;"> <input type="submit" id="UploadButton" value="开始上传" disabled>
- <br>图片描述: <input type="text" name="imgdes" id="imgdes" size="40" >
- <div style="border:1 solid #808080;background:#E0E0E0;width100%;height:20px;color:#606060;padding:5px;">
- <table border="0"><tr><td width="60" id="PreviewImg">预览区</td><td id="MsgList" valign="top"></td></tr></table>
- </div>
- </fieldset>
- </form>
- </body>
- </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传前台控制检测程序 v0.6</title>
<style>
body,td{font-size:12px;}
</style>
<script language=javascript>
var ImgObj=new Image(); //建立一个图像对象
var AllImgExt=".jpg|.jpeg|.gif|.bmp|.png|"//全部图片格式类型
var FileObj,ImgFileSize,ImgWidth,ImgHeight,FileExt,ErrMsg,FileMsg,HasCheked,IsImg//全局变量图片相关属性
//以下为限制变量
var AllowExt=".jpg|.gif|.doc|.txt|" //允许上传的文件类型 ?为无限制 每个扩展名后边要加一个"|" 小写字母表示
//var AllowExt=0
var AllowImgFileSize=70; //允许上传图片文件的大小 0为无限制 单位:KB
var AllowImgWidth=500; //允许上传的图片的宽度 ?为无限制 单位:px(像素)
var AllowImgHeight=500; //允许上传的图片的高度 ?为无限制 单位:px(像素)
HasChecked=false;
function CheckProperty(obj) //检测图像属性
{
FileObj=obj;
if(ErrMsg!="") //检测是否为正确的图像文件 返回出错信息并重置
{
ShowMsg(ErrMsg,false);
return false; //返回
}
if(ImgObj.readyState!="complete") //如果图像是未加载完成进行循环检测
{
setTimeout("CheckProperty(FileObj)",500);
return false;
}
ImgFileSize=Math.round(ImgObj.fileSize/1024*100)/100;//取得图片文件的大小
ImgWidth=ImgObj.width //取得图片的宽度
ImgHeight=ImgObj.height; //取得图片的高度
FileMsg="/n图片大小:"+ImgWidth+"*"+ImgHeight+"px";
FileMsg=FileMsg+"/n图片文件大小:"+ImgFileSize+"Kb";
FileMsg=FileMsg+"/n图片文件扩展名:"+FileExt;
if(AllowImgWidth!=0&&AllowImgWidth<ImgWidth)
ErrMsg=ErrMsg+"/n图片宽度超过限制。请上传宽度小于"+AllowImgWidth+"px的文件,当前图片宽度为"+ImgWidth+"px";
if(AllowImgHeight!=0&&AllowImgHeight<ImgHeight)
ErrMsg=ErrMsg+"/n图片高度超过限制。请上传高度小于"+AllowImgHeight+"px的文件,当前图片高度为"+ImgHeight+"px";
if(AllowImgFileSize!=0&&AllowImgFileSize<ImgFileSize)
ErrMsg=ErrMsg+"/n图片文件大小超过限制。请上传小于"+AllowImgFileSize+"KB的文件,当前文件大小为"+ImgFileSize+"KB";
if(ErrMsg!="")
ShowMsg(ErrMsg,false);
else
ShowMsg(FileMsg,true);
}
ImgObj.onerror=function(){ErrMsg='/n图片格式不正确或者图片已损坏!'}
function ShowMsg(msg,tf) //显示提示信息 tf=true 显示文件信息 tf=false 显示错误信息 msg-信息内容
{
msg=msg.replace("/n","<li>");
msg=msg.replace(//n/gi,"<li>");
if(!tf)
{
document.all.UploadButton.disabled=true;
FileObj.outerHTML=FileObj.outerHTML;
MsgList.innerHTML=msg;
HasChecked=false;
}
else
{
document.all.UploadButton.disabled=false;
if(IsImg)
PreviewImg.innerHTML="<img src='"+ImgObj.src+"' width='60' height='60'>"
else
PreviewImg.innerHTML="非图片文件";
MsgList.innerHTML=msg;
HasChecked=true;
}
}
function CheckExt(obj)
{
ErrMsg="";
FileMsg="";
FileObj=obj;
IsImg=false;
HasChecked=false;
PreviewImg.innerHTML="预览区";
if(obj.value=="")return false;
MsgList.innerHTML="文件信息处理中...";
document.all.UploadButton.disabled=true;
FileExt=obj.value.substr(obj.value.lastIndexOf(".")).toLowerCase();
if(AllowExt!=0&&AllowExt.indexOf(FileExt+"|")==-1) //判断文件类型是否允许上传
{
ErrMsg="/n该文件类型不允许上传。请上传 "+AllowExt+" 类型的文件,当前文件类型为"+FileExt;
ShowMsg(ErrMsg,false);
return false;
}
if(AllImgExt.indexOf(FileExt+"|")!=-1) //如果图片文件,则进行图片信息处理
{
IsImg=true;
ImgObj.src=obj.value;
CheckProperty(obj);
return false;
}
else
{
FileMsg="/n文件扩展名:"+FileExt;
ShowMsg(FileMsg,true);
}
}
function SwitchUpType(tf)
{
if(tf)
str='<input type="file" name="file1" onchange="CheckExt(this)" style="width:180px;">'
else
str='<input type="text" name="file1" onblur="CheckExt(this)" style="width:180px;">'
document.all.file1.outerHTML=str;
document.all.UploadButton.disabled=true;
MsgList.innerHTML="";
}
</script>
</head>
<body>
<form enctype="multipart/form-data" method="POST" action="./upload.jsp?folderName=uploadImage&relativePath=../../" onsubmit="return HasChecked;">
<fieldset style="width: 400px; height: 60;padding:2px;">
<legend><font color="#FF0000">图片来源</font></legend>
<input type="radio" name="radio1" checked onclick="SwitchUpType(true);">本地<input type="radio" name="radio1" onclick="SwitchUpType(false);">远程:<input type="file" name="file1" onchange="CheckExt(this)" style="width:180px;"> <input type="submit" id="UploadButton" value="开始上传" disabled>
<br>图片描述: <input type="text" name="imgdes" id="imgdes" size="40" >
<div style="border:1 solid #808080;background:#E0E0E0;width100%;height:20px;color:#606060;padding:5px;">
<table border="0"><tr><td width="60" id="PreviewImg">预览区</td><td id="MsgList" valign="top"></td></tr></table>
</div>
</fieldset>
</form>
</body>
</html>
upload.jsp
- <%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
- <%@ page language="java" import="java.io.PrintWriter"%>
- <%@ page language="java" import="java.io.*"%>
- <%@ page language="java" import="java.util.UUID"%>
- <%@ page language="java" import="java.util.Enumeration"%>
- <%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
- <%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
- <%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%>
- <%
- response.setHeader("Cache-Control", "no-cache");
- response.setCharacterEncoding("gb2312");
- PrintWriter xmlout = response.getWriter();
- String uuid = UUID.randomUUID().toString();
- //文件的fileURL
- String fileURL = "";
- // 上传文件名
- String fileName = null;
- //取得文件描述
- String fileDesName = "";
- StringBuffer sb = new StringBuffer();
- String result = "";
- try
- {
- //得到此源文件的目录
- String realPath = getServletContext().getRealPath("");
- String contentPath = request.getContextPath();
- String requestURL = request.getRequestURL().toString();
- String realURL = requestURL.split(contentPath)[0] + contentPath;
- //上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
- String folderName = request.getParameter("folderName");
- //根据不同层级../../的路径不同
- String relativePath = request.getParameter("relativePath");
- //文件的相对路径
- String comparafileName = "";
- // 将上传文件存放在saveDirectory
- String saveDirectory = realPath + "/" + folderName;
- System.out.println("saveDirectory= " + saveDirectory);
- File uploadPath = new File(saveDirectory);
- if (!uploadPath.exists())
- {
- uploadPath.mkdir();
- }
- // 上传文件的大小限制在10 MB
- int maxPostSize = 10 * 1024 * 1024;
- //实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
- FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
- // 上传文件
- MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "gb2312",policy);
- StringBuffer filenametemp = new StringBuffer();
- filenametemp.append(uuid);
- //在iidd后面加一下划线"-"以便和文件名称区分出来
- filenametemp.append("-");
- //取得文件描述
- fileDesName = multi.getParameter("imgdes");
- //System.out.println("文件描述:"+ fileDesName);
- // 取得所有上传文件名称
- Enumeration filesname = multi.getFileNames();
- while (filesname.hasMoreElements())
- {
- String name = (String) filesname.nextElement();
- //文件上传的完整路径
- File f = multi.getFile(name);
- //文件名称
- fileName = multi.getFilesystemName(name);
- if (fileName != null)
- {
- String oldFilename=fileName;
- int idx=oldFilename.lastIndexOf(".");
- String extention=oldFilename.substring(idx);
- //取文件名
- String newFilename=oldFilename.substring(0,idx);
- //得到不重复的文件名,用iidd加文件名
- String sServerFileName = (String)filenametemp.toString();
- sServerFileName =sServerFileName+newFilename+extention;
- File sServerFile= new File(saveDirectory+"//" + sServerFileName);
- f.renameTo(sServerFile);
- String FileName = sServerFile.getName();
- //放在上两级目录下(根目录的文件夹下)
- //String comparafileName = "../../" + folderName + "/" + FileName;
- comparafileName = relativePath + folderName + "/" + FileName;
- System.out.print("文件的相对路径:"+comparafileName);
- fileURL = realURL + "/" + folderName + "/" + FileName;
- }
- }
- sb.append("<html><body>");
- sb.append("<input id = /"UploadIsSucces/" type=/"hidden/" value=/"1/" />");
- sb.append("图片已经上传成功!");
- sb.append("<br /> 图片描述:");
- sb.append(fileDesName);
- sb.append("<br />图片url:");
- sb.append(fileURL);
- String img = "<br /><img src='" + fileURL + "' />";
- String urll = "http://localhost:8080/pictureupload/uploadImage/877700ca-bac3-4c07-92d5-0458010865e4-aa.jpg";
- String img2="<br/><a herf=/"http://localhost:8080/pictureupload/upload.html/"> <img src='"+urll+"'/></a>";
- sb.append(img);
- sb.append(img2);
- sb.append("</body></html>");
- result = sb.toString();
- //System.out.println(rs);
- }
- catch(Exception e)
- {
- System.out.println("message=" + e.getMessage());
- //Posted content length of 42654262 exceeds limit of 10485760
- String message = e.getMessage();
- if(message.indexOf("Posted content length of") !=-1)
- {
- String content = message.split("length of ")[1].split(" exceeds")[0];
- int ct = Integer.parseInt(content);
- String limit = message.split("limit of ")[1];
- int lt = Integer.parseInt(limit);
- result = "对不起,你上传的图片大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
- }
- else
- {
- result = "上传失败";
- }
- e.printStackTrace();
- }
- try
- {
- xmlout.write(result);
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- finally
- {
- xmlout.flush();
- xmlout.close();
- }
- %>
<%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
<%@ page language="java" import="java.io.PrintWriter"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.util.UUID"%>
<%@ page language="java" import="java.util.Enumeration"%>
<%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("gb2312");
PrintWriter xmlout = response.getWriter();
String uuid = UUID.randomUUID().toString();
//文件的fileURL
String fileURL = "";
// 上传文件名
String fileName = null;
//取得文件描述
String fileDesName = "";
StringBuffer sb = new StringBuffer();
String result = "";
try
{
//得到此源文件的目录
String realPath = getServletContext().getRealPath("");
String contentPath = request.getContextPath();
String requestURL = request.getRequestURL().toString();
String realURL = requestURL.split(contentPath)[0] + contentPath;
//上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
String folderName = request.getParameter("folderName");
//根据不同层级../../的路径不同
String relativePath = request.getParameter("relativePath");
//文件的相对路径
String comparafileName = "";
// 将上传文件存放在saveDirectory
String saveDirectory = realPath + "/" + folderName;
System.out.println("saveDirectory= " + saveDirectory);
File uploadPath = new File(saveDirectory);
if (!uploadPath.exists())
{
uploadPath.mkdir();
}
// 上传文件的大小限制在10 MB
int maxPostSize = 10 * 1024 * 1024;
//实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
// 上传文件
MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "gb2312",policy);
StringBuffer filenametemp = new StringBuffer();
filenametemp.append(uuid);
//在iidd后面加一下划线"-"以便和文件名称区分出来
filenametemp.append("-");
//取得文件描述
fileDesName = multi.getParameter("imgdes");
//System.out.println("文件描述:"+ fileDesName);
// 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
//文件上传的完整路径
File f = multi.getFile(name);
//文件名称
fileName = multi.getFilesystemName(name);
if (fileName != null)
{
String oldFilename=fileName;
int idx=oldFilename.lastIndexOf(".");
String extention=oldFilename.substring(idx);
//取文件名
String newFilename=oldFilename.substring(0,idx);
//得到不重复的文件名,用iidd加文件名
String sServerFileName = (String)filenametemp.toString();
sServerFileName =sServerFileName+newFilename+extention;
File sServerFile= new File(saveDirectory+"//" + sServerFileName);
f.renameTo(sServerFile);
String FileName = sServerFile.getName();
//放在上两级目录下(根目录的文件夹下)
//String comparafileName = "../../" + folderName + "/" + FileName;
comparafileName = relativePath + folderName + "/" + FileName;
System.out.print("文件的相对路径:"+comparafileName);
fileURL = realURL + "/" + folderName + "/" + FileName;
}
}
sb.append("<html><body>");
sb.append("<input id = /"UploadIsSucces/" type=/"hidden/" value=/"1/" />");
sb.append("图片已经上传成功!");
sb.append("<br /> 图片描述:");
sb.append(fileDesName);
sb.append("<br />图片url:");
sb.append(fileURL);
String img = "<br /><img src='" + fileURL + "' />";
String urll = "http://localhost:8080/pictureupload/uploadImage/877700ca-bac3-4c07-92d5-0458010865e4-aa.jpg";
String img2="<br/><a herf=/"http://localhost:8080/pictureupload/upload.html/"> <img src='"+urll+"'/></a>";
sb.append(img);
sb.append(img2);
sb.append("</body></html>");
result = sb.toString();
//System.out.println(rs);
}
catch(Exception e)
{
System.out.println("message=" + e.getMessage());
//Posted content length of 42654262 exceeds limit of 10485760
String message = e.getMessage();
if(message.indexOf("Posted content length of") !=-1)
{
String content = message.split("length of ")[1].split(" exceeds")[0];
int ct = Integer.parseInt(content);
String limit = message.split("limit of ")[1];
int lt = Integer.parseInt(limit);
result = "对不起,你上传的图片大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
}
else
{
result = "上传失败";
}
e.printStackTrace();
}
try
{
xmlout.write(result);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
xmlout.flush();
xmlout.close();
}
%>