关于springmvc+maybaits+spring下的文件上传问题(jxl)

今日,在做项目的过程中需要一个导入文件的功能,经过研究,总结以下几点:
1. 导入相应的jar包,本人使用的是jxl的相关jar包。(commons-fileupload-1.2.1、commons-io-2.4、jxl-2.6.12、xmlbeans-2.3.0)仅支持:后缀为.xls的excel文件
相应的下载位置为http://pan.baidu.com/s/1skI6cKd
2. 将下载的jar包加入到lib目录下,然后在spring-mvc.xml中进行相关的配置:配置如下:
3. <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="104857600" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>

4. 在jsp页面中必须加入的一句是:enctype="multipart/form-data"
5. 本人项目加视频页面form的相关代码(排版不一,只是看那句代码位置)

<form action="doGuidenceStuScoreImport.do" method="post" name="form1"
        enctype="multipart/form-data">
         <input type="hidden" id="type" name="type" value="excelStuCourseScore">
        <div style="float:left">
            <table border="1" width="600">
                <tr>
                    <td width="400"><input type="hidden" name="_method"
                        value="post"> 学生成绩信息文件(*.xls): 
                        </td>
                        <td>
                        <input type="file"
                        name="file" onchange="fileChange(this);"> 
                    </td>
                    <td width="70"><input type="button" value=" 提 交 "
                        onclick="Check()"> <br></td>
                </tr>
            </table>
        </div>
    </form>
  1. 导入的excel表格解析问题:在Service层进行的处理,(首先是在控制器层进行一个文件处理,在Service进行解析)代码片段:
@Repository(value = "excelService")
@Transactional
public class ExcelService {

    /** 
    * 说明 导入成绩表格解析 temp1存放学号 temp2存放姓名 temp3存放班级名称
    * @author 丁乐晓
    * @time:2016年6月21日 上午9:40:31 
    */
    public static List<Score> AnalysisStuScore(File file) {
        List<Score> StuScore = new ArrayList<Score>();
        try {   
            Workbook book = Workbook.getWorkbook(file);
            // 获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            for (int r = 1; r < sheet.getRows(); r++) {// 行
                int nullCell = 0;// 存储空单元格的数量
                int c = 0;// 列
                String result = ""; // 存储单元格内容
                Score tcm = new Score();// 存储单行数据
                // 学号
                Cell cell1 = sheet.getCell(c++, r);
                result = cell1.getContents().trim();// trim去首尾空格,防止因为数据出错。
                if (result.equalsIgnoreCase("")) {
                    nullCell++;
                } else {
                    if (DictionaryService.findStudentByCode(result) != null) {
                        String stuId = DictionaryService.findStudentByCode(result).getId();
                        tcm.setStu_id(stuId);
                        tcm.setTemp1(result);
                    } else {
                        tcm.setTemp1(result);
                    }
                    // 学生姓名
                    cell1 = sheet.getCell(c++, r);
                    result = cell1.getContents().trim();// trim去首尾空格,防止因为数据出错。
                    if (result.equalsIgnoreCase("")) {
                        nullCell++;
                    } else {
                        tcm.setTemp2(result);
                    }
                    // 班级名称
                    cell1 = sheet.getCell(c++, r);
                    result = cell1.getContents().trim();
                    if (result.equalsIgnoreCase("")) {
                        nullCell++;
                    } else {
                        tcm.setTemp3(result);
                    }

                    // 得分
                    cell1 = sheet.getCell(c++, r);
                    result = cell1.getContents().trim();
                    if (result.equalsIgnoreCase("")) {
                        nullCell++;
                    } else {
                        tcm.setScore(result);
                    }

                    if (nullCell > 4)// 本行数据共读取了4个null
                        break;
                    else
                        StuScore.add(tcm);// 本行记录放入列表
                }
            }
            book.close();

        } catch (Exception e) {
            System.out.println(e);
        }
        return StuScore;
    }
}
  1. 控制器层的文件地址处理:
@RequestMapping(value = "teacher/doGuidenceStuScoreImport.do", method = RequestMethod.POST)
    public String StuScoreImport(MultipartHttpServletRequest request,
            ModelMap modelMap, HttpSession se) throws Exception {
        // 获取当前用户登录信息
        Teacher tea = (Teacher) se.getAttribute("current_user");
        String tea_id = tea.getId();// 获取教师ID
        // 导入类型
        String smsyear = se.getAttribute("smsyear").toString();
        String smster = se.getAttribute("semester").toString();
        String courseid = se.getAttribute("corid").toString();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = request;
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next()
                        .toString());

                if (file != null) {
                    String file_type = "excelStuCourseScore";

                    String project_path = request.getSession()
                            .getServletContext().getRealPath("/");
                    String fileName = file.getOriginalFilename();
                    /*
                     * String filePosition = "WEB-INF/uploadedfiles/Import/" +
                     * fileName;
                     */
                    String filepos = "Import" + "/" + file_type + "_";
                    String filePosition = "Import" + "/" + file_type + "_"
                            + fileName;
                    String real_path = Constants.FILE_ROUTE;
                    String file_path = project_path + real_path + filePosition;
                    /*
                     * String file_pa = real_path +
                     * "WEB-INF/uploadedfiles/Import/";
                     */
                    String file_pa = project_path + real_path + filepos;
                    // 使用getSize()方法获得文件长度,以此决定允许上传的文件大小。
                    file.transferTo(new File(file_path));// 使用transferTo(dest)方法将上传文件写到服务器上指定的文件
                    // 文件的属性
                    File f = new File(file_pa + fileName);
                    // 判断导入数据表类型
                    List<Score> stuscoreList = ExcelService.AnalysisStuScore(f);

                    HttpSession session = request.getSession();
                    session.setAttribute("stuscoreList", stuscoreList);
                    String infor = "";
                    int b;
                    int i = 0;// 记录验证成功的条数
                    for (Score stc : stuscoreList) {
                        /*
                         * // 避免出现null的问题 if (stc.getTemp1() == null)
                         * stc.setTemp1("");
                         */
                        // 学号 姓名
                        if (stc.getStu_id() == null
                                || stc.getStu_id().equals("")) {
                            infor = infor + "学号不存在!";
                        } else {
                            String stcname = DictionaryService.findStudent(
                                    stc.getStu_id()).getTrue_name();
                            String stcname1 = stc.getTemp2();
                            if (!stcname1.equals(stcname)) {
                                infor = infor + "学生姓名与学号不匹配!";
                            }
                            Score sc = new Score();
                            sc.setTea_id(tea_id);
                            sc.setCourse_id(courseid);
                            sc.setStu_id(sc.getStu_id());
                            sc.setTerm(smster);
                            sc.setYear(smsyear);
                            int num = scoreService.selectCount(sc);
                            if (num > 0) {
                                infor = infor + "该课程该生的成绩已存在!";
                            }
                        }
                        if (stc.getScore() == null || stc.getScore().equals("")) {
                            infor = infor + "成绩不能为空!";
                        }

                        // 验证成功
                        if (infor.trim().equals("")) {
                            infor = "无";
                            i++;
                        }
                        stc.setTemp4(infor.trim());
                        infor = "";
                    }
                    modelMap.put("successCheck", "您辛苦了,共有 " + i + " 条记录被成功验证通过");
                    Courses course = coursesService.selectByID(courseid);
                    String coursename = course.getCourse_name();// 课程名
                    String teaname = tea.getTure_name();// 教师姓名
                    modelMap.put("coursename", coursename);
                    modelMap.put("stucoreList", stuscoreList);
                    modelMap.put("teaname", teaname);
                }
            }
        }
        return "teacher/scoreImport";
    }

这个地方是自己写的一个地址,为在项目根目录下的一个用于临时存放导入的文件的地方
这里写图片描述
这里写图片描述
8. 之后进行的便是自己的一些相应操作,如判断,保存等等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值