您的位置:首页 > 其它

利用MultipartFile实现文件上传

2017-07-28 10:57 393 查看
导入需要使用的jar包
commons-fileupload-xxx.jar    
 commons-io-xxx.jar 等等
在mvc配置文件中:
<!-- 文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="5400000"/>
</bean>

前端使用表单提交
<form id="Form5" name="Form5" action="<%=basePath%>kh/importFile">
选择上传文件:<input type="file" name="file1" id="file1">

<input type="button" id="imp_btn" onclick="importFile()" value="导 入">

</form>
在提交之前要先判断提交的文件是否为空,是否为表格,然后ajaxSubmit
$("#imp_btn").attr("disabled",true);
var path = $("#file1").val();
if(path==null || path==""){
alert("请选择上传文件");
$("#imp_btn").removeAttr("disabled");
return false;
}
var okText = /xls|xlsx/; //这里是允许的扩展名
var newFileName = path.split('.'); //这是将文件名以点分开,因为后缀肯定是以点什么结尾的.
newFileName = newFileName[newFileName.length-1];//这个是得到文件后缀,因为split后是一个数组所以最后的那个数组就是文件的后缀名.newFileName.length为当前的长度,-1则为后缀的位置,因为是从0开始的
//开始检查后缀
if (newFileName.search(okText) == -1) {//search如果没有刚返回-1.这个如果newFileName在okText里没有,则为不允许上传的类型. .
alert("上传文件格式必须为表格");//提示
//location.reload();
$("#imp_btn").removeAttr("disabled");
return false;
}
$("#Form5").ajaxSubmit({
type: "Post",
dataType:"jsonp",
//data: $('#Form2').serialize(),
//url:"<%=basePath%>kh/importFile",
async:true,
success:function(result){
result = $.parseJSON(result.replace(/<.*?>/ig,""));
//console.log(result);
//新增成功
if(result.state==1){
alert(result.message);
$("#imp_btn").removeAttr("disabled");
reloadKhInfo();
//window.location.href='<%=basePath %>mobile/week/fotoThirdPage?zbid='+result.data;
// window.event.returnValue=false;
}else{//新增失败
alert(result.message);
$("#imp_btn").removeAttr("disabled");
//$("#imp_btn").removeAttr("disabled");
reloadKhInfo();
return false;
}
},error:function(result){
alert("插入失败");
$("#imp_btn").removeAttr("disabled");
reloadKhInfo();
}
});
后台接收:
@RequestMapping(value="importFile")
@ResponseBody
public JsonResult importFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request,HttpServletResponse response) {
//request.setCharacterEncoding("utf-8");
//response.setCharacterEncoding("text/html,charset=utf-8");
try{
List<Enterprise> enterprises=importFile.importEmployeeByPoi(file1);
int start=enterprises.size();
Object[] obj= enterprises.toArray();
Enterprise[] qiye=new Enterprise[start];
for(int i=0;i<obj.length;i++){
qiye[i]=(Enterprise) obj[i];
}
//清除openid为空的 taxno为空的 name为空的对象
for(int i=0;i<qiye.length;i++){
if(qiye[i].getOpenid()==null || qiye[i].getOpenid().equals("") ||
qiye[i].getTaxno()==null || qiye[i].getTaxno().equals("") ||
qiye[i].getName()==null || qiye[i].getName().equals("") ){
qiye[i]=null;
}
}
//清除openid不存在于yhxx表的
for(int i=0;i<qiye.length;i++){
if(qiye[i]!=null){
int count=khglMapper.checkOpenid(qiye[i].getOpenid());
if(count==0){
qiye[i]=null;
}
}
}
//清除taxno重复的
for(int i=0;i<qiye.length;++i){
if(qiye[i]!=null){
int count=khglMapper.checkTaxno(qiye[i].getTaxno());
if(count>0){
qiye[i]=null;
}
}

}
//清除name重复的
for(int i=0;i<qiye.length;++i){
if(qiye[i]!=null){
int count=khglMapper.checkName(qiye[i].getName());
if(count>0){
qiye[i]=null;
}
}

}
//清除结束后,将List再插入wx_enterprise表内
int sum=0;
List<Enterprise> list=new ArrayList<Enterprise>();
for(int i=0;i<qiye.length;i++){
if(qiye[i]!=null){
list.add(qiye[i]);
}
}
if(list.size()>0){
for(int i=0;i<list.size();i++){
//Enterprise enterprise=new Enterprise();
khglMapper.addKhInfo2(list.get(i));
createVerify2(String.valueOf(list.get(i).getId()),list.get(i).getOpenid());
sum++;
}
//sum=khglMapper.insertList(list);
}

return new JsonResult(1,"导入成功"+sum+"条,导入失败"+(start-sum)+"条");
//return new JsonResult(1,"导入成功");
}catch(Exception e ){
e.printStackTrace();
return new JsonResult(0,"导入异常");
}

}
importEmployeeByPoi方法(03和07有一点 不同,需要注意一下):
public static List<Enterprise> importEmployeeByPoi(/*String filePath*/MultipartFile mifile) {

List<Enterprise> infos = new ArrayList<Enterprise>();
Enterprise enterprise = null;

try {
InputStream fis =null;
//获取一个绝对地址的流
//fis = new FileInputStream(filePath);
fis=mifile.getInputStream();
//创建Excel工作薄
Workbook book=null;
try {
book = new XSSFWorkbook(fis);
} catch (Exception ex) {
book = new HSSFWorkbook(fis);
}
//HSSFWorkbook hwb = new HSSFWorkbook(fis);
//得到第一个工作表
Sheet sheet = book.getSheetAt(0);
Row row = null;
//日期格式化
// DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
//遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
for(int i = 0; i < book.getNumberOfSheets(); i++) {
sheet = book.getSheetAt(i);
//遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数
//System.out.println(sheet.getPhysicalNumberOfRows());
for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
row = sheet.getRow(j);
enterprise = new Enterprise();

//此方法调用getCellValue(HSSFCell cell)对解析出来的数据进行判断,并做相应的处理
if(row.getCell(0) != null && !"".equals(row.getCell(0))) {
if(getCellValue(row.getCell(0)).equals("")){
enterprise.setId(0);
}else{
enterprise.setId(Integer.valueOf(getCellValue(row.getCell(0))));
}
//(Integer.valueOf(==""?0:getCellValue(row.getCell(0))));
}
if(row.getCell(1) != null && !"".equals(row.getCell(1))) {
enterprise.setOpenid(getCellValue(row.getCell(1)));
}

if(row.getCell(2) != null && !"".equals(row.getCell(2))) {
try {
enterprise.setSubscribe_time((getCellValue(row.getCell(2))));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(3) != null && !"".equals(row.getCell(3))) {
try {
enterprise.setGzzt(getCellValue(row.getCell(3)));
} catch (Exception e) {
e.printStackTrace();
}
}

//System.out.println(getCellValue(row.getCell(4)));
//System.out.println(getCellValue(row.getCell(4))==null);
//System.out.println("".equals(getCellValue(row.getCell(4))));
if(row.getCell(4) != null && !"".equals(row.getCell(4))) {
try {
enterprise.setQxgzsj((getCellValue(row.getCell(4))));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(5) != null && !"".equals(row.getCell(5))) {
try {
enterprise.setName(getCellValue(row.getCell(5)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(6) != null && !"".equals(row.getCell(6))) {
try {

enterprise.setTaxno(getCellValue(row.getCell(6)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(7) != null && !"".equals(row.getCell(7))) {
try {
enterprise.setTaxoffice(getCellValue(row.getCell(7)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(8) != null && !"".equals(row.getCell(8))) {
try {
enterprise.setAddress(getCellValue(row.getCell(8)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(9) != null && !"".equals(row.getCell(9))) {
try {
enterprise.setBank_name(getCellValue(row.getCell(9)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(10) != null && !"".equals(row.getCell(10))) {
try {
enterprise.setBank_account(getCellValue(row.getCell(10)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(11) != null && !"".equals(row.getCell(11))) {
try {
enterprise.setContacter1(getCellValue(row.getCell(11)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(12) != null && !"".equals(row.getCell(12))) {
try {
enterprise.setTel1(getCellValue(row.getCell(12)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(13) != null && !"".equals(row.getCell(13))) {
try {
enterprise.setContacter2(getCellValue(row.getCell(13)));
} catch (Exception e) {
e.printStackTrace();
}
}
if(row.getCell(14) != null && !"".equals(row.getCell(14))) {
try {
enterprise.setTel2(getCellValue(row.getCell(14)));
} catch (Exception e) {
e.printStackTrace();
}
}
infos.add(enterprise);
}

}
} catch (IOException e) {
e.printStackTrace();
}
return infos;
}
还需要判断数据格式:
//判断从Excel文件中解析出来数据的格式
private static String getCellValue(Cell cell){
String value = null;
//简单的查检列类型
switch(cell.getCellType())
{
case Cell.CELL_TYPE_STRING://字符串
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC://数字
long dd = (long)cell.getNumericCellValue();
value = dd+"";
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
case Cell.CELL_TYPE_FORMULA:
value = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BOOLEAN://boolean型值
value = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
value = String.valueOf(cell.getErrorCellValue());
break;
default:
value="";
break;
}
return value;
}
----------------------------------------------------------------------------------------------------------------------
一开始做文件上传,使用的是直接获取file文件的path:  var path = $("#file1").val(); 
可是这样在google浏览器里面获取的是fakepath,假路径,没法用。在ie里面倒是可以
    
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: