问题描述:前台通过表单提交文件数据,服务器获取
apache的commons-fileupload : http://commons.apache.org/fileupload/
解决方案:
1. jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<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">
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
<font style="color:red">只支持office文件在线预览,如doc,docx,ppt,pptx,xls,xlxs</font></br>
<input type="file" name="file"/></br>
<input type="submit" value="在线预览">
</form>
</body>
</html>
web.xml里配置了upload对应的servlet
2. 文件接收处理
/**
* Servlet implementation class
* 向文件预览服务器直接发送文件
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String fileRootPath;
// 做插入数据库的操作
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Logger log = Logger.getLogger(DownLoadServlet.class);
//初始化文件根目录
fileRootPath=PropertiesUtil.readValue("upload.filesystem.path");
//判断提交表单是否为multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//新建一个磁盘文件存储factory
DiskFileItemFactory factory=new DiskFileItemFactory();
//当文件太大时,因为虚拟机能使用的内存是有限的,所以要通过临时文件来实现上传的保存
//设置临时文件的临界值
String maxMemoryThreshold = PropertiesUtil.readValue("upload.tempfile.maxMemorySize");
factory.setSizeThreshold(Integer.valueOf(maxMemoryThreshold));
//设置临时文件路径
String tempDirectory =fileRootPath+"/"+ PropertiesUtil.readValue("upload.tempfile.path");
File tempDir=new File(tempDirectory);
factory.setRepository(tempDir);
//新建文件操作实例
ServletFileUpload upload =new ServletFileUpload(factory);
String maxsize=PropertiesUtil.readValue("upload.file.maxSize");
upload.setSizeMax(Integer.valueOf(maxsize));
//解析上传文件数据
List<?> items = new ArrayList<FileItem>();
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Iterator iter=items.iterator();
while (iter.hasNext()) {
FileItem item=(FileItem)iter.next();
if(item.isFormField()){
//如果是普通表单字段
String name=item.getFieldName();
String value=item.getString();
}else{
//如果是文件字段
String filedName=item.getFieldName();
String filename=item.getName();
String contentType=item.getContentType();
long sizeInBytes =item.getSize();
// TODO 处理上传数据
String savepath=fileRootPath+PropertiesUtil.readValue("upload.file.path");
File uploadedFile =new File(savepath+"/"+filename);
try {
item.write(uploadedFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}