springmvc 文件上传

第一次使用springmvc上传文件的时候碰到了一些问题,走了一些弯路,在此记下,希望大家少走一些弯路,节约一点时间

言归正传,碰到的问题如下:

1、form表单提交总是报错,意思就是string不能转换成multipartFile

    解决办法:在form表单加上文件上传的标记   enctype="multipart/form-data";

2、springmvc默认用multipartFile接收文件,网上有很多上传的工具类都是用file文件上传,这时候大家可能就想到了这两者如何转换了,当初我也是这么想的,可是转换并不好用,不同浏览器之间有的可以有的却不可以,会出问题,所以这时候就不要这么用

解决办法:把工具类中的file改成mutipartFile,springmvc拿到multipartFile的时候直接用流进行上传就没有任何问题

代码如下:

大家只看红色部分就好了

jsp:

                    <input type='text' name='textfield' id='textfield' class='txt' />
                    <input type="file" name="fileField" class="file" id="fileField" size="20" onchange="document.getElementById('textfield').value=this.value"/>
                    <input type="submit" name="submission" class="btn" value="批量导入" onclick="uploadFile()"/>

java:


    @RequestMapping(value="/uploadFile",method={RequestMethod.POST,RequestMethod.GET})
    @Transactional(isolation=Isolation.DEFAULT ,propagation=Propagation.REQUIRED ,readOnly=false)
    public String uploadFile(@RequestParam("fileField")MultipartFile files ,@RequestParam("textfield")String textfield,ModelMap model,HttpServletRequest request ) {
        HashMap<String,Object> parameters=new HashMap<String, Object>();
        List<Questions> readExcel =new ArrayList<Questions>();
        int m=0;
        StringBuffer sb=new StringBuffer();
        try {
            ImportExcel ie=new ImportExcel();

                String suffix=textfield.substring(textfield.lastIndexOf(".")+1);
                if ("xls".equals(suffix)) {
                      readExcel = ie.readXls(files);//调用工具类方法
                }else if ("xlsx".equals(suffix)) {
                      readExcel = ie.readXlsx(files);
                }else {
                    model.addAttribute("message", "导入的不是excel文件!");
                    readExcel = null;
                }
            
            if (null!=readExcel&&readExcel.size()!=0) {
                for (Questions questions : readExcel) {
                    m++;
                    parameters.put("questionName", questions.getQuestionName());
                    List<Questions> questionList= questionService.getQuestionByQuestionName(parameters);
                    
                    if(questionList.size()==0){
                    String departmentId = departmentService.getDepartmentId(questions.getDepartmentName());
                    questions.setDepartmentName(departmentId);
                    int i=questionService.saveQuestion(questions);
                    List<Options> options = questions.getOptions();
                    if (null!=options&&options.size()!=0) {
                        for (Options option : options) {
                            option.setQuestionId(i);
                            optionService.saveOption(option);
                        }
                    }
                    }else{
                        sb.append(m).append(",");
                    }
                }
                String error=sb.toString();
                if(!error.isEmpty()){
                    error="第"+error.substring(0, error.length()-1)+"行试题重复,拒绝导入";
                }
                
                model.addAttribute("error", error);
            }
                
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            logger.error("=======批量添加试题出错======"+e);
        }
        
        return "forward:/do/question/list";
    }
工具类:

public class ImportExcel {
    private static Logger logger=Logger.getLogger(QuestionManagerController.class);
    
    
     public  List<Questions> readXlsx(MultipartFile file) throws IOException {
            InputStream is = file.getInputStream();//核心就这一步
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
            Questions questions = null;
            List<Questions> list = new ArrayList<Questions>();

            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
                XSSFSheet hssfSheet = xssfWorkbook.getSheetAt(numSheet);
                if (hssfSheet == null) {
                    continue;
                }
                // 循环行Row

原文地址:https://www.cnblogs.com/shaoyang/p/5328251.html