标签:
上传图片:
jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="css/newstyle.css" rel="stylesheet" type="text/css">
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/commfn.js" type="text/javascript" charset="utf-8"></script>
<script src="js/vli.js"></script>
<script type="text/javascript">
function openUpload_(val){
var functionId = val;/*选取当前选中项*/
//alert(functionId);
openUpload(functionId,‘JPG,GIF,JPEG,PNG‘,‘1‘,callback);
}
function openUpload(functionId,fileType,maxSize,callback){
var url = "userAction.do?method=goFileUpload&";
if(functionId!=null){
url = url + "functionId="+functionId+"&";
}
if(fileType!=null){
url = url + "fileType="+fileType+"&";
}
if(maxSize!=null){
url = url + "maxSize="+maxSize;
}
var win = window.showModalDialog(url,"","dialogWidth:300px;dialogHeight:150px;scroll:no;status:no");
if(win != null){
var arrWin = win.split(",");
callback(arrWin[0],arrWin[1],arrWin[2]);
}
}
/**
* 回调函数,获取上传文件信息
* realName真实文件名
* saveName文件保存名
* maxSize文件实际大小
*/
function callback(realName,saveName,maxSize){
alert("aa");
//回调后其它操作
}
</script>
<style type="text/css">
.ll td {
border-top: #CaCaCa 1px solid;
border-left: #CaCaCa 1px solid;
border-bottom: #CaCaCa 1px solid;
}
.111 td {
border-left: #CaCaCa 1px solid;
border-bottom: #CaCaCa 1px solid;
}
</style>
</head>
<body scroll="no" leftmargin="0" topmargin="0">
<form name="projForm" id="projForm" method="post" action="/userAction.do?=addDrUsersNew" focus="userName" enctype="multipart/form-data" >
<input type="hidden" id="id" name="id" value="${user.id}" />
<input name="userName" type="hidden" value="${pageForm.userName }" />
<input type="hidden" name="pageStyle" value="goPage" /> <input
type="hidden" name="currentPageNum"
value="${pageForm.currentPageNum }" /> <input type="hidden"
name="totalPageNum" value="${pageForm.totalPageNum }" />
<table border="0" cellspacing="0" cellpadding="0" width="100%" height="100%">
<tr>
<td height="25" bgcolor="#accff5"> <img
src="images/body/toptitle1.gif" align="absMiddle" border="0" /> <strong>添加用户</strong>
</td>
</tr>
<tr>
<td valign="top" height="25">
<!-- 内容开始 -->
<table id="tdcycle1" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td height="25" bgcolor="#accff5" colspan="4"> <img
src="images/body/toptitle1.gif" align="absMiddle" border="0" /> <strong>货主信息</strong>
</td>
</tr>
<tr class="ll">
<td width="150" height="25" align="right">身份证:</td>
<td height="25" align="left" style="border-right:1px solid #CaCaCa" colspan="3">
<input type="hidden" name="photo" id="photo_"></input>
<input type="button" onclick="openUpload_(this.value)" value="上传身份证"/>
</td>
</tr>
</table>
</table>
<tr>
<td id="splitpage" height="25" align="center">
<a href="javascript:submitform();"><img src="images/body/confirm.gif" border="0" /></a></td>
</tr>
</table>
</td>
<td id="splitpage" height="25" align="center"><a
href="javascript:submitform();"><img
src="images/body/confirm.gif" border="0" /></a></td>
</tr>
</table>
</form>
<!-- ui-dialog -->
<div id="dialog"></div>
<div id="loading_img"
style="position: absolute; background: #FFFFFF; display: none; z-index: 2; width: 128; height: 128; border-left: solid #5084B8 1px; border-top: solid #5084B8 1px; border-bottom: solid #5084B8 1px; border-right: solid #5084B8 1px;"
cellspacing="0" cellpadding="0" oncontextmenu="return false">
<img src=../images/loading.gif width="128" height="128">
</div>
</body>
</html>
jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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>Insert title here</title>
</head>
<body>
<h5>文件上传</h5><hr/>
<form id="file_upload_id" name="file_upload_name" action="../wlgl/fileUpload.do" method="post" enctype="multipart/form-data">
<input type="hidden" name="functionId" value="${functionId}"/>
<input type="hidden" name="fileType" value="${fileType}"/>
<input type="hidden" name="maxSize" value="${maxSize}"/>
<div><input type="file" name="file_upload"/></div>
<c:if test="${maxSize!=null}">
<div style="font: 12">文件最大不能超过${maxSize}MB</div>
</c:if>
<c:if test="${fileType!=null}">
<div style="font: 12">文件格式必须是:${fileType}</div>
</c:if>
<div><input type="submit" value="上传"/></div>
</form>
</body>
</html>
web.xml
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>
com.hysoft.action.FileUploadServlet
</servlet-class>
<init-param>
<!-- 上传文件内存缓冲区的大小,大于这个值将直接写入临时磁盘存储目录 -->
<param-name>threshold</param-name>
<param-value>10485760</param-value><!-- 1M -->
</init-param>
<init-param>
<!-- 服务器端上传文件的临时磁盘存储目录 -->
<param-name>repository</param-name>
<param-value>/uploadFile/</param-value>
</init-param>
<init-param>
<!-- 允许单个上传文件大小的最大值 -->
<param-name>fileSizeMax</param-name>
<param-value>8388608</param-value><!-- 8M=2*1024*1024 -->
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/fileUpload.do</url-pattern>
</servlet-mapping>
java:
package com.hysoft.action;
import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import com.hysoft.utils.UUID;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 8088769669368270752L;
// 日志记录
Logger log = Logger.getLogger(this.getClass().getName());
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@SuppressWarnings({ "unchecked", "unused" })
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ActionErrors errors = new ActionErrors();
// 保存用户信息
//Users u = uBusi.addDrUserNew(uForm, errors);
// 保存图片
String temp = request.getSession().getServletContext().getRealPath("/") + "temp"; // 临时目录
String path = request.getSession().getServletContext().getRealPath("/") + "uploadFile"; // 上传文件存放目录
temp = temp.replace("wlgltemp", "wlgl/temp");
path = path.replace("wlgluploadFile", "wlgl/uploadFile");
//获取并解析文件类型和支持最大值
String functionId = request.getParameter("functionId");
String fileType = request.getParameter("fileType");
String maxSize = request.getParameter("maxSize");
DiskFileItemFactory factory = new DiskFileItemFactory();
//最大缓存
factory.setSizeThreshold(5*1024);
//设置临时文件目录
factory.setRepository(new File(temp));
ServletFileUpload upload = new ServletFileUpload(factory);
if(maxSize!=null && !"".equals(maxSize.trim())){
//文件最大上限
upload.setSizeMax(Integer.valueOf(maxSize)*1024*1024);
}
try {
//获取所有文件列表
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if(!item.isFormField()){
//文件名
String fileName = item.getName();
//检查文件后缀格式
String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
if(fileType!=null && !"".equals(fileType.trim())){
boolean isRealType = false;
String[] arrType = fileType.split(",");
for (String str : arrType) {
if(fileEnd.equals(str.toLowerCase())){
isRealType = true;
break;
}
}
if(!isRealType){
//提示错误信息:文件格式不正确
log.error("文件格式不正确!");
}
}
//创建文件唯一名称
String uuid = UUID.create("file");
//真实上传路径
StringBuffer sbRealPath = new StringBuffer();
sbRealPath.append(path).append("/").append(uuid).append(".").append(fileEnd);
//写入文件
File file = new File(sbRealPath.toString());
item.write(file);
//上传成功,向父窗体返回数据:真实文件名,虚拟文件名,文件大小
StringBuffer sb = new StringBuffer();
sb.append("window.returnValue=‘").append(fileName).append(",").append(uuid).append(".").append(fileEnd).append(",").append(file.length()).append("‘;");
sb.append("window.close();");
log.info("上传文件成功,JS信息:"+sb.toString());
}
}
}catch (Exception e) {
//提示错误:比如文件大小
log.error("上传失败,文件大小不能超过"+maxSize+"M!",e);
log.error("上传文件异常!",e);
}
}
}
标签:
原文地址:http://www.cnblogs.com/fanc/p/5798468.html