美文网首页
3、文件上传

3、文件上传

作者: ltjxwxz | 来源:发表于2017-09-02 18:02 被阅读0次

    首先application.yml配置项如下

    multipart:
      enabled: true
      file-size-threshold: 30MB
      max-file-size: -1
    

    具体参数说明如下:
    (1) multipart.enabled
    开启分段(multi-part)上传支持。(默认值: true。)
    (2)multipart.file-size-threshold
    大于该阈值的文件会写到磁盘上。这里的值可以使用MB或KB后缀来表明是兆字节还是千字节。(默认值: 0。)
    (3)multipart.location
    上传文件的中间存放位置。
    (4)multipart.max-file-size
    最大文件大小。这里的值可以使用MB或KB后缀来表明是兆字节还是千字节。(默认值:1MB。-1表示无限制)
    (5)multipart.max-request-size
    最大请求大小。这里的值可以使用MB或KB后缀来表明是兆字节还是千字节。(默认值:10MB。)

    pom.xml需要加入

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency> 
    
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.2</version>
    </dependency>
    
    

    前端

    <form id="edit-profile" class="form-horizontal" action="<%=basePath %>upload/beforeUploadExcel" 
    method="post" enctype="multipart/form-data"/>
        <div class="control-group">
            <label class="control-label" for="username">文件</label>
            <div class="controls">
                <input type="file" name="file" class="input-medium disabled"/>
                <p class="help-block"></p>
            </div>
        </div>
        <br />
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">下一步</button>
            <button class="btn">取消</button>
        </div>
    </form>
    

    controlller

    @RequestMapping(value = "/beforeUploadExcel", method = RequestMethod.POST)
    public String beforeUploadExcel(MultipartHttpServletRequest multiReq, Map<String, Object> model) {
        // 从session中获取用户信息
        User userLogin = (User) session.getAttribute(SessionKeyConstant.USER_INFO);
        
        // 获取上传的文件MultipartFile
        MultipartFile uploadFile = multiReq.getFile("file");
        String fileNameAll = multiReq.getFile("file").getOriginalFilename();
        String fileName = fileNameAll.substring(0, fileNameAll.lastIndexOf("."));
        // 获取上传文件名的后缀
        String fileSuffix = fileNameAll.substring(fileNameAll.lastIndexOf("."));
        logger.info("上传文件全名:" + fileNameAll);
        logger.info("上传文件名:" + fileName);
        logger.info("文件后缀名:" + fileSuffix);
        
        // 如果文件为空
        if (uploadFile == null) {
            model.put(PageCodeEnum.KEY, PageCodeEnum.FILEISNULL);
            return "/selectfile";
        } else if(!fileNameAll.endsWith("xlsx") && !fileNameAll.endsWith("xls")) {
            // 文件格式不对
            model.put(PageCodeEnum.KEY, PageCodeEnum.FILEILLEGAL);
            return "/selectfile";
        } else if(!fileService.hasRightName(fileNameAll, userLogin.getUserid())) {
            // 文件名不包含项目名
            model.put(PageCodeEnum.KEY, PageCodeEnum.FILENAMEISWRONG);
            return "/selectfile";
        } else {
            // 判断该用户是否有映射关系,如果存在,返回usersheetList
            List<UserSheet> userSheetList = uploadService.hasMapping(userLogin.getUserid(), fileName);
            session.setAttribute(userLogin.getUserid() + ReturnConstant.USER_SHEET_LIST_LAST, userSheetList);
            
            // 文件保存到本地
            File commonFile = fileService.saveExcel(multiReq, userLogin);
            // 获取sheet页名字
            Map<String, List<String>> sheetTitleUpload = ExcelUtil.readSheetTitle(commonFile);
            logger.info("用户上传的sheetTitleUpload:" + sheetTitleUpload);
            session.setAttribute(userLogin.getUserid() + SessionKeyConstant.USER_SHEET_TITLE_UPLOAD, sheetTitleUpload);
            return "/selectsheet";
        }
    }
    

    service:存储文件到本地

    /**
     * 把文件保存到 resources目录下,并返回File对象
     * @param multiReq
     * @return
     */
    public File saveExcel(MultipartHttpServletRequest multiReq, User user) {
        String fileNameAll = multiReq.getFile("file").getOriginalFilename();
        String fileName = fileNameAll.substring(0, fileNameAll.lastIndexOf("."));
        logger.info("上传文件名为:" + fileName);
        String path = FileService.class.getResource("/").getPath().substring(1);
        // 创建一个以用户名为名字的文件夹
        File pathFile = new File(path + user.getName());
        pathFile.mkdir();
        File saveFile = new File(path + user.getName() + "/" + fileNameAll);
        ByteArrayInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = (ByteArrayInputStream) multiReq.getFile("file").getInputStream();
            // 文件写到resources目录下
            outputStream = new FileOutputStream(saveFile);
            byte[] temp = new byte[1024];
            int i = inputStream.read(temp);
            while (i != -1) {
                outputStream.write(temp, 0, temp.length);
                outputStream.flush();
                i = inputStream.read(temp);
            }
            // 存到session
            session.setAttribute(user.getUserid() + SessionKeyConstant.FILENAME, fileName);
            session.setAttribute(user.getUserid() + SessionKeyConstant.SAVEFILE, saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return saveFile;
    }
    

    说明:如果没用spring boot,做文件上传报错:[org.springframework.web.multipart.MultipartException: The current request is not a multipart request]
    可在spring-mvc.xml中添加

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
    

    参考:https://stackoverflow.com/questions/15008049/org-springframework-web-multipart-multipartexception-the-current-request-is-not

    相关文章

      网友评论

          本文标题:3、文件上传

          本文链接:https://www.haomeiwen.com/subject/xialjxtx.html