前言:项目用的是struts1,想要上传文件必须用jsp,传输指定类型写struts1标签,这样局限性太强,果断放弃,写一个servlet来实现。
web.xml
<servlet>
<display-name>UploadServlet</display-name>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.phlx.product.wx.action.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet.action</url-pattern>
</servlet-mapping>
servlet
package ********;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.human.util.SysConst;
/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// 上传文件存储目录
private static final String UPLOAD_DIRECTORY = "upload";
// 上传配置
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
/**
* 上传数据及保存文件
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
// 检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
// 如果不是则停止
PrintWriter writer = response.getWriter();
writer.println("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
factory.setSizeThreshold(MEMORY_THRESHOLD);
// 设置临时存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大文件上传值
upload.setFileSizeMax(MAX_FILE_SIZE);
// 设置最大请求值 (包含文件和表单数据)
upload.setSizeMax(MAX_REQUEST_SIZE);
// 中文处理
upload.setHeaderEncoding("UTF-8");
// 构造临时路径来存储上传的文件
// 这个路径相对当前应用的目录
//String uploadPath = request.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;
// 获取配置文件中项目绝对路径,并截取到WebRoot\\
String queryPath = SysConst.getConfField("queryPath");
queryPath = queryPath.substring(0, queryPath.indexOf("WEB-INF"));
// 获取上传的图片
String uploadPath = "wxproduct\\img\\" + System.currentTimeMillis();
String filedest = queryPath + uploadPath;
System.out.println("filedest:" + filedest);
// 如果目录不存在则创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<String, String>();
try {
// 解析请求的内容提取文件数据
@SuppressWarnings("unchecked")
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 迭代表单数据
for (FileItem item : formItems) {
// 处理不在表单中的字段
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = uploadPath + File.separator + fileName;
File storeFile = new File(filedest);
// 在控制台输出文件的上传路径
System.out.println(filedest);
// 保存文件到硬盘
item.write(storeFile);
request.setAttribute("message",
"文件上传成功!");
map.put("errcode", "0");
map.put("picUrl", uploadPath);
map.put("msg", "上传成功");
}
}
}
} catch (Exception ex) {
map.put("errcode", "-1");
map.put("picUrl", "-1");
map.put("msg", "上传失败");
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
Gson gson = gsonBuilder.create();
String json = gson.toJson(map);
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
out.write(json);
out.flush();
out.close();
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}
这里主要说前台实现,用jquery实现ajax异步上传,上传没问题。
upload.html
<!DOCTYPE html>
<html>
<head>
<title>消息查询</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="X-UA-Compatible" content="IE=8" >
<script type="text/javascript" src="../../js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../../js/jquery.easyui.min1.4.4.js"></script>
<script type="text/javascript" src="../../js/easyui-lang-zh_CN.js"></script>
</head>
<body>
<img style="display:none;" id="imgFile"/>
<input id="text" type="text" name="text"/>
<form method="post" id="fm11" enctype="multipart/form-data" >
<input name="uploadFile" id="uploadFile" type="file"
onchange="submitForm(this.value)" style="position:absolute;left:0;top:0;
width:100%;height:100%;z-index:999;opacity:0;filter:Alpha(Opacity=0)"/>
</form>
</body>
<script type="text/javascript">
function submitForm(tvalue){
var aa = tvalue.split(".");
if(aa[aa.length-1]=='gif'||aa[aa.length-1]=='jpg'||aa[aa.length-1]=='bmp'
||aa[aa.length-1]=='png'||aa[aa.length-1]=='jpeg'){
$('#fm11').form('submit',{
url:"/WebRoot/UploadServlet.action",
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errcode=='0'){
$("#text").val(result.picUrl);
$("#imgFile").attr("src","/WebRoot/"+result.picUrl);
$("#imgFile").show();
//$("#uploadFile").val(result.picUrl);
} else {
alert("上传失败!");
/* $.messager.show({
title: '操作不成功!',
msg: result.msg
}); */
}
}
});
}else{
alert("文件格式错误,请重新选择图片!");
/* $.messager.alert({
title: '文件格式错误',
msg: '请选择图片!'
}); */
}
}
</script>
</html>
但是现在的问题是,系统使用的是IE8,file标签的样式是不能修改的
现在有两种方式类实现:
1、将file隐藏,用其他案件来触发file的click事件,实现修改的目的,
但是,这种方式在ie上是不实现的,应为处于安全考虑,ie不允许代码实现触发上传功能,可以选择文件,提交显示,访问被拒绝,直接就是不走后台的。
2、把form放在a标签中,大小与a标签对齐,是file标签透明:opacity:0;
“opacity:0;”在ie8以下是不兼容的,所以得用filter:Alpha(Opacity=0)
最终代码如下:替换body中所有代码
<img style="display:none;" id="imgFile"/>
<input id="text" type="text" name="text"/>
<a style="position:relative;display:block;width:100px;height:30px;background:#EEE;border:1px solid #999;text-align:center;" href="javascript:void(0);" >上传
<div style="position:absolute;left:0;top:0;width:100%;height:100%;z-index:999;opacity:0;">
<form method="post" id="fm11" enctype="multipart/form-data" >
<input name="uploadFile" id="uploadFile" type="file" onchange="submitForm(this.value)" style="position:absolute;left:0;top:0;width:100%;height:100%;z-index:999;opacity:0;filter:Alpha(Opacity=0)"/>
</form>
</div>
</a>