1.上传文件至服务器
2.解析Excel文件并返回数据集合
3.将数据保存到服务器
框架======Spring+(基于注解的)SpringMVC和Mybatis=====
第一步:
前台:
jsp文件采用的是uploadify
<div id="fileQueue"></div>
<input type="file" id="brandFile">
js:<script type="text/javascript">
//当DOM(文档对象模型)载入就绪可以查询及操纵时绑定一个要执行的函数。
$(document).ready(function(){
$("#brandFile").uploadify({
//前台请求后台的url 不可忽略的参数 获取session的id
'uploader':'<%=request.getContextPath()%>/brand/analyzeXml.jhtml;',
//插件自带 不可忽略的参数
'swf': '<%=request.getContextPath()%>/js/uploadify/uploadify.swf',
//撤销按钮的图片路径
'cancelImg': '<%=request.getContextPath() %>/js/uploadify/uploadify-cancel.png',
//如果为true 为自动上传 在文件后 为false 那么它就要我们自己手动点上传按钮
'auto': true,
//可以同时选择多个文件 默认为true 不可忽略
'multi': false,
//设置上传队列容器DOM元素的ID,如果为false则自动生成一个队列容器。
//'queueID': false,
'queueID': 'fileQueue',
// fileTypeDesc: '*.xls;*.xlsx',//文件后缀描述
//fileTypeExts: '**.xls;*.xlsx',//文件后缀限制
//给上传按钮设置文字
'buttonText': 'poi解析',
//上传后队列是否消失
'removeCompleted': true,
//上传完成后每个文件消失的间隔
'removeTimeout' : 1,
/*上传文件的大小限制允许上传文件的最大 大小。 这个值可以是一个数字或字 符串。
如果它是一个字符串,它接受一个单位(B, KB, MB, or GB)。
默认单位为KB您可以将此值设置为0 ,没有限制,
单个文件不允许超过所设置的值 如果超过 onSelectError时间被触发*/
'fileSizeLimit':'100KB',
//上传对象的名字 相当file标签中的name属性;
'fileObjName' : 'brandFile',
//上传文件的个数
'uploadLimit': 1,
//返回一个错误,选择文件的时候触发
'onSelectError':function(file, errorCode, errorMsg){
switch(errorCode) {
case -100:
alert("上传的文件数量已经超出系统限制的"
+$('#brandFile').uploadify('settings','queueSizeLimit')+"个文件!");
break;
case -110:
alert("文件 ["+file.name+"] 大小超出系统限制的"
+$('#brandFile').uploadify('settings','fileSizeLimit')+"大小!");
break;
case -120:
alert("文件 ["+file.name+"] 大小异常!");
break;
case -130:
alert("文件 ["+file.name+"] 类型不正确!");
break;
}
},
//上传到服务器,服务器返回相应信息到data里
'onUploadSuccess':function(file, data, response){
alert("上传成功");
alert(data);
},
//当单个文件上传出错时触发
'onUploadError': function (file, errorCode, errorMsg, errorString) {
alert("上传失败");
}
});
});
</script>
后台:
myBatis结合uploadify的文件上传
@RequestMapping("/analyzeXml")
public void analyzeXml(@RequestParam MultipartFile brandFile,HttpServletRequest request,HttpServletResponse response) {
//上传xml文件
InputStream inputs;
try {
inputs = brandFile.getInputStream();
String fileName = brandFile.getOriginalFilename();
String path = getRealPath("/uploadFile", request);
System.out.println(path);
String uploadFileName = FileUtil.uploadFile(inputs, fileName, path);
//解析xml文件
List<Brand> brandList = AnalyzePoiBrand.Analyze_Poi_Brand(getRealPath("/uploadFile/"+uploadFileName, request));
//导入数据库
brandService.addBrandListPoi(brandList);
//响应客户端
outJoin("{\"success\":true}", response);
} catch (IOException e) {
e.printStackTrace();
}
}
获取上传文件名:FileUtil封装类中的uploadFile()方法
/***
* <pre>uploadFile(springMVC文件上传 传inputStream)
* 修改备注:
* @param inputs
* @param fileName
* @param folderPath
* @return</pre>
*/
public static String uploadFile(InputStream inputs, String fileName, String folderPath) {
// 上传物理文件到服务器硬盘
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
String uploadFileName = null;
try {
// 构建输入缓冲区,提高读取文件的速度
bis = new BufferedInputStream(inputs);
// 自动建立文件夹
File folder = new File(folderPath);
if (!folder.exists()) {
folder.mkdirs();
}
// 为了保证上传文件的唯一性,可以通过uuid来解决
// 为了避免中文乱码问题则新生成的文件名由uuid+原来文件名的后缀组成
uploadFileName = UUID.randomUUID().toString()+getSuffix(fileName);
// 构建写文件的流即输出流
fos = new FileOutputStream(new File(folderPath+"/"+uploadFileName));
// 构建输出缓冲区,提高写文件的性能
bos = new BufferedOutputStream(fos);
// 通过输入流读取数据并将数据通过输出流写到硬盘文件夹
byte[] buffer = new byte[4096];// 构建4k的缓冲区
int s = 0;
while ((s=bis.read(buffer)) != -1) {
bos.write(buffer, 0, s);
bos.flush();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
bos = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
fos = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
bis = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (inputs != null) {
try {
inputs.close();
inputs = null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return uploadFileName;
}
原来的后缀名的获取getSuffix()
封装的将Excel问键转换成JavaBeanList数据
private static String getSuffix(String fileName) {
int index = fileName.lastIndexOf(".");
String suffix = fileName.substring(index);
return suffix;
}
public class AnalyzePoiBrand {
public static List<Brand> Analyze_Poi_Brand(String brandPath) {
List<Brand> brandModelList = new ArrayList<Brand>();
try {
//通过路径获取要解析的文件
InputStream inputStream = new FileInputStream(brandPath);
//将文件进行解析(把获取到的文件转换成sheet表)
XSSFWorkbook workBook = new XSSFWorkbook(inputStream);
//获取sheet从第零行开始
XSSFSheet hssfSheet = workBook.getSheetAt(0);
//获取总行数
int lastRowNum = hssfSheet.getLastRowNum();
//必须用《=因为从下表数。只用《那么会少数一条数据
for (int i = 0; i <= lastRowNum; i++) {
Brand brand = new Brand();
XSSFRow hrow = hssfSheet.getRow(i);
String brandName = hrow.getCell(0).getStringCellValue();
brand.setBrandName(brandName);
brandModelList.add(brand);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return brandModelList;
}
}
以上是我再项目的使用