上传csv格式文件,利用commons-fileupload

来源:互联网 发布:自动对比度算法 编辑:程序博客网 时间:2024/06/01 07:45

1、添加jar包依赖

<dependency>
         <groupId>commons-fileupload</groupId>
         <artifactId>commons-fileupload</artifactId>
         <version>1.3.3</version>
     </dependency>


2、配置bean

<!-- 要上传文件,就要引入这个bean -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
          p:defaultEncoding="UTF-8" p:maxUploadSize="104857600">
    </bean>


3、批量导入按钮

            <button type="button" id="importButton" class="btn btn-success" onclick="importDialog()" style="width:150px">批量导入
            </button>

      对应js:

//导入数据对话框
function importDialog() {
    $("#file").val("");
    $("#uploadDiv").dialog({
        resizable: false,
        height: 280,
        width: 480,
        modal: true
    });
}

弹出对应的对话框:

<!--批量导入-->
<div id="uploadDiv" class="showBox" style="margin-left:5px;margin-top:5px;display:none" title="批量导入界面">
<form id="inputForm1" name="inputForm1" action="/psadmin/uploadCPBrand.do" method="post" enctype="multipart/form-data" onsubmit="return false">
<table width="100%"  class="up_table">
<tr>
    <td width="30px">路径</td>
<td align=left><input class="form-control" type="file" id="file" name="file"></input></td>
<td ><button class="btn btn-info" onclick="uploadCPBrand()"><span><span>导入</span></span></button></td>
</tr>
</table>
</form>
<br>
<!--<HR align=left width=100% color=lightBlue SIZE=1>-->
<table width=100% cellspacing=0 cellpadding=0 border=1px class="up_table">
<tr>
    <th width="30px"></th>
<th >母品牌</th>
<th >子品牌</th>
</tr>
<tr onmouseover="this.style.backgroundColor='#F0F8FF'" onmouseout="this.style.backgroundColor=''">
    <td align="center">1</td>
<td>中兴</td>
<td>努比亚</td>
</tr>
<tr onmouseover="this.style.backgroundColor='#F0F8FF'" onmouseout="this.style.backgroundColor=''">
     <td  align="center">2</td>
<td>泸州老窖</td>
<td>老泸州,泸州原浆酒</td>
</tr>
</table>
<br>
<div class="up_info_t">提示</div>
<div class="up_info_c">
    1、上传文件必须为csv格式。
    <br>2、上传文件只包含母品牌,子品牌,子母品牌以Tab键分隔,例如:中兴努比亚。
</div>
</div>


导入按钮对应js:

function uploadCPBrand() {
    var files = $("#file").val();
    if (files == null || files == "") {
        alert("请选择文件");
        return false;
    } else if (files.substr(files.length - 4, 4).toLowerCase().match("(^.csv)") == null) {
        alert("请选择.csv格式文件");
        return false;
    } else {
        if (confirm('确定上传?')) {
            $("#inputForm1")[0].submit();


        }
    }
}

注意:如果要将参数带入URL,请用下面的代码:

var url = "/ps-admin-nimitz/system/uploadAccount.do?roleId="+roleId+"&&role="+role;
            $("#inputForm1").attr("action", url);
            $("#inputForm1")[0].submit();


4、后台代码:

controller类中方法:

    

@Controller
public class ChildAndParentBrandMining {
private final Logger log = SearchLogger.getLogger(ChildAndParentBrandMining.class);
@Autowired
    private CPBrandService cpbrandService;
@Autowired
    private PsInfoService psInfoService;
@Autowired
private ShowLogService showLogService;

private int seg = 10;// 默认一页的记录数    

    // 批量上传
    @RequestMapping("/uploadCPBrand.do")
    public String uploadCPBrand(@RequestParam MultipartFile file, HttpServletRequest request, ModelMap model/*, Authentication authentication*/) throws Exception {
     String userId = request.getRemoteUser();
     BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
        String line;
        List<CPBrandBean> data = new LinkedList<CPBrandBean>();
        while( (line = br.readLine()) != null ){
         try{
         String[] token = line.split("\t");
         if( token == null || token.length != 2 )continue;
         CPBrandBean brandBean = new CPBrandBean();
             brandBean.setParentBrand(token[0]);
             brandBean.setChildBrand(token[1]);
             brandBean.setSource("本地");
         data.add(brandBean);
         }catch(Exception ex){
         log.error("上传文件有脏数据",ex);
         }
        }
        int count = cpbrandService.addBatch(data);
        if(count>0){
         String behavior = "本地导入子母品牌数据";
            log.info("用户"+userId+behavior);
            showLogService.addLog(userId, "子母品牌挖掘", behavior);
        }
        IOUtils.closeQuietly(br);
return "redirect:/psadmin/CPBrandList.do";//必须用重定向,不能直接用childAndParentBrandWeb方法,否则URL不会重定向
    }

}

        /**
   * 子母品牌挖掘
   **/
@RequestMapping("/CPBrandList.do")
public String childAndParentBrandWeb(ModelMap modelMap, HttpServletRequest request, @RequestParam(required = false) String keyword,
             @RequestParam(required = false) String page) {
int totalpages;
String newKeyword = keyword == null ? "" : keyword.trim();
     String page1 = page == null ? "1" : page.trim();
     int pages = Integer.parseInt(page1);
     int maxCount = cpbrandService.getTotalCount(newKeyword.toLowerCase());
     if (maxCount % seg == 0) {
         totalpages = maxCount / seg;
     } else {
         totalpages = maxCount / seg + 1;
     }
     List<CPBrandBean> CPBrandBeanList = new ArrayList<CPBrandBean>();
     if (totalpages == 0) {
         pages = 0;
     } else {
         if (pages > totalpages) {
             pages = totalpages;
         }
         int start = (pages - 1) * seg + 1;
         CPBrandBeanList = cpbrandService
                    .getQueryResult(newKeyword.toLowerCase(), start, -1);
         modelMap.put("CPBrandBeanList", CPBrandBeanList);
     }
     modelMap.put("CPBrandBeanList", CPBrandBeanList);
     modelMap.put("newKeyword", newKeyword);
     modelMap.put("pages", totalpages);
     modelMap.put("currentpage", pages);
psInfoService.baseInfo(request, modelMap);
modelMap.put("component", "child_parent_brand");
     return "/admin/index.ftl";
}

   


service类:

package com.suning.web.service;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.suning.web.bean.CPBrandBean;
import com.suning.web.dao.CPBrandDao;


@Service
public class CPBrandService {
@Autowired
    private CPBrandDao cpbrandDao;
// 返回查询结果个数
    public int getTotalCount(String newKeyword) {
        return cpbrandDao.getTotalCount(newKeyword);
    }
    // 查询
    public List<CPBrandBean> getQueryResult(String newKeyword, int start, int segment) {
        return cpbrandDao.getQueryResult(newKeyword, start, segment);
    }
    //修改
    public boolean brandUpdate(String parentBrand, String newChildBrand, String source) {
        return cpbrandDao.brandUpdate(parentBrand, newChildBrand, source);
    } 
    //删除任务映射
    public boolean brandDelete(String parentBrand) {
        return cpbrandDao.brandDelete(parentBrand.trim());
    }
    //导入子母品牌数据
    public int addBatch(List<CPBrandBean> data){
    return cpbrandDao.addBatch(data);
    }
}


dao类:

package com.suning.web.dao;


import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;


import com.suning.web.bean.CPBrandBean;


@Repository
public class CPBrandDao {
private int seg = 10;
@Autowired
    private JdbcTemplate jdbcTemplate;

    public int addBatch(final List<CPBrandBean> data){
    String sql = "INSERT INTO ps_child_parent_brand(parent_brand,child_brand,source) VALUES(?,?,?) ON DUPLICATE KEY UPDATE child_brand=?,source=?";
    int[] res = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){


@Override
public void setValues(PreparedStatement ps, int i)
throws SQLException {
ps.setString(1, data.get(i).getParentBrand());
ps.setString(2, data.get(i).getChildBrand());
ps.setString(3, data.get(i).getSource());
ps.setString(4, data.get(i).getChildBrand());//更新的数据
ps.setString(5, data.get(i).getSource());//更新的数据
}


@Override
public int getBatchSize() {
return data.size();
}
    
    });
    return res[0];
    }
}


对应的数据表设计:

CREATE TABLE `ps_child_parent_brand` (
  `parent_brand` varchar(100) NOT NULL DEFAULT '' COMMENT '母品牌',
  `child_brand` varchar(100) DEFAULT NULL COMMENT '子品牌',
  `source` varchar(100) DEFAULT 'HIVE' COMMENT '数据来源',
  PRIMARY KEY (`parent_brand`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='子母品牌表';

原创粉丝点击