AngularJS上传文件

网上关于angularJS做上传文件基本上会用angular-fileinput这样一个BootStrap和angularJS整合做的一个上传文件优化,然而我们实际使用中,根本不会这样用,首先前端可能有使用其他样式会与bootstrap的样式冲突,其次需要引入fileinput的一系列js文件,挺不方便的。
那么,angularJS要怎么简单的做文件上传呢?

首先,先写一个js文件,直接把下面这段复制进去
其次,解释一下代码内容:
$("#excel")[0]为固定写法,其中$("#excel")为获取id为excel的html标签,这个标签肯定是一个input框,类型为file,[0]获取第一个(一般html中id是唯一的);
url为后端访问的地址,只需修改这两处就可以实现上传文件到后端了
使用时,将uploadService注入你的控制器,调用uploadService.upload()方法即可

app.service('uploadService',function($http){
    /*
    anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json。
    通过设置 ‘Content-Type’: undefined,这样浏览器会帮我们把 Content-Type 设置为
    multipart/form-data.
   通过设置 transformRequest: angular.identity ,anjularjs transformRequest function将序列化 我们的 formdata object.
    */
    this.upload = function () {
        var formData=new FormData();
        formData.append("file",$("#excel")[0].files[0]);
        return $http({
            method:'POST',
            url:"attachmentUpload",
            data: formData,
            headers: {'Content-Type':undefined},
            transformRequest: angular.identity
        });
    }
})

后端代码就没什么好说的了

	@ResponseBody
	@PostMapping("/attachmentUpload")
	public String parseExcel(MultipartFile file){
        try {
            InputStream fileInputStream = file.getInputStream();
            ExcelReader excelReader = ExcelUtil.getReader(fileInputStream);
            //自定义标题别名
            Map<String, String> alias = Maps.newLinkedHashMap();
            alias.put(ExcelConstants.NUM, "num");
            alias.put(ExcelConstants.PROPOSERNAME, "proposerName");
            alias.put(ExcelConstants.HOUSEHOLDREGION, "houseHoldName");
            alias.put(ExcelConstants.LOCALITYREGION, "localityName");
            alias.put(ExcelConstants.CARDNUM, "cardNum");
            alias.put(ExcelConstants.NOTARY, "notary");
            alias.put(ExcelConstants.USE_COUNTRY, "use_country");
            alias.put(ExcelConstants.LANGUAGE, "language");
            alias.put(ExcelConstants.AUTH_NUM, "auth_num");
            alias.put(ExcelConstants.USE, "use");
            alias.put(ExcelConstants.REMARK, "remark");
            excelReader.setHeaderAlias(alias);
            List<ExcelOrderDTO> list = excelReader.readAll(ExcelOrderDTO.class);
            return "";
        } catch (IOException e) {
//            SYS_LOGGER.error("excel解析异常",e);
        }
        return null;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值