Springmvc文件上传

来自ling
跳转至: 导航搜索
<div class="fileinput fileinput-new ">
<div class="fileinput-preview thumbnail" style="width: 50px; height: 50px;"  ngf-select ng-model="commodityItem.uploadfile" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="10MB">
<img ng-if="commodityItem.uploadfile!=null" ngf-thumbnail="commodityItem.uploadfile || '/thumb.jpg'">     
<img ng-if='commodityItem.uploadfile==null' ng-src='{{commodityItem.showPicUrl}}'>
</div>
</div>
	@ResponseBody
	@RoleAnnotation(roles=RoleDef.ECOMMERCE_ADMIN)
	@RequestMapping(value = "/saveCommoditySliderWithFile", method = RequestMethod.POST)
	public void saveCommoditySliderWithFile(@RequestParam(value="file",required=false) MultipartFile file,
			@RequestParam(value="data",required=false) String data) {
		CommodityPicRes slider =JSON.parseObject(data, CommodityPicRes.class);
		Attachment attachment;
		try {
			attachment=fileManager.saveFile(file, slider.getCommodityId().toString(), AttachmentDef.commodity_main_pic);
			attachment.setDes(slider.getDes());
			attachment.setSortOrder(slider.getSortOrder());
			attachment.setUsed(slider.getUsed());
			commodityService.update(attachment);
			if(slider.getId()!=null){
				attachment=(Attachment) commodityService.get(Attachment.class, slider.getId());
				attachment.setFlag(TableColnumDef.FLAG_DISABLED);
				commodityService.update(attachment);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("文件保存出错");
		}
	}

上传的excel文件解析

MultipartFile readline

/**
     * 解析txt和csv的文件内容为Employee集合
     *
     * @param file
     * @param seperator
     * @return
     * @throws Exception
     */
    private List<BaseOrgVo> readEmployeeContentByLine(MultipartFile file, String seperator) throws Exception {
        List<BaseOrgVo> results = new ArrayList<>();
        int lineNum = 1;
        try (
                InputStream in = file.getInputStream();
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
        ) {
            String line;
            //网友推荐更加简洁的写法
            while ((line = br.readLine()) != null) {
                BaseOrgVo vo = new BaseOrgVo();
                // 一次读入一行数据
                String[] contents = line.split(seperator);
                for (int i = 0; i < contents.length; i++) {
                    //TODO 对象转换
                }
                results.add(vo);
                lineNum++;
            }
        } catch (IOException e) {
            String msg = "文件解析错误,第" + lineNum + "行:" + e.getMessage();
            logger.error(msg);
            throw new BusinessException(msg);
        }
        return results;
    }

TenantApiController CloudApiApplicationTests