文件上传-angular

1)HTML

<form enctype="multipart/form-data" name="fileForm">
                    <div class="form-group">
                        <label class="col-sm-1 control-label" style="margin-top: 3px;"><span style="color: red">*</span>模块名称</label>
                        <div class="col-sm-3">
                            <select name="moduleId" ng-model="moduleId">
                                <option value="">请选择模块</option>
                                <option value="322">系统操作</option>
                                <option value="324">实战模块</option>
                                <option value="325">视频培训</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-1 control-label" style="margin-top: 3px;">请选择文件</label>
                        <div class="col-sm-3">
                            <input type="file" file-model="file">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-1 control-label" style="margin-top: 3px;"><span style="color: red">*</span>文件描述</label>
                        <div class="col-sm-3">
                            <textarea ng-model="fileDesc" name="fileDesc" cols="30" rows="10"
                                      placeholder="描述少于30个字"></textarea>

                            <p ng-show="fileDesc.length>30" style="color:red">内容少于30字</p>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-3 col-sm-offset-1">
                            <input type="button" class="btn btn-default"
                                   ng-disabled="(moduleId==null || fileDesc.trim().length==0)|| fileDesc.length>30 "
                                   ng-click="save()" value="上传"/>
                            <input type="button" class="btn btn-default" style="margin-left: 28px;" ng-click="fnClose()"
                                   value="取消"/>
                        </div>
                    </div>
                </form>
View Code

 

2)JS

$http({
                method: 'post',
                url: '/lpfx/api/file/upload',
                headers: {
                    'Content-Type': undefined
                },
                transformRequest: function (data) {
                    var formData = new FormData();
                    formData.append('moduleId', data.moduleId);
                    formData.append('fileDesc', data.fileDesc);
                    formData.append('file', data.file);
                    return formData;
                },
                data: {
                    moduleId: $scope.moduleId,
                    fileDesc: $scope.fileDesc,
                    file: document.querySelector('input[type=file]').files[0],
                }
            }).then(function (response) {
                if (response && response.data.success) {
                    $rootScope.searchUpload();
                    $timeout(function(){
                        notification.notify('上传成功', 'success');
                    },150);
                } else {
                    $rootScope.loading = false;
                    if (response.data.errorCode == 10) {
                        notification.notify(response.data.errorMsg, 'danger');
                    } else {
                        notification.notify('上传失败', 'danger');
                    }
                }
            },function(errorcode){
                $rootScope.loading = false;
            });
View Code

 

3)Java

@RequestMapping("/upload")
    @ResponseBody
    public Object fileUpload(@RequestParam("fileDesc") String fileDesc, @RequestParam("moduleId") Long moduleId,
                             @RequestParam("file") MultipartFile file) throws IOException {
        Long maxSize = Long.valueOf(RuntimeEnvironmentUtil.getValue("lpfx.upload", "lpfx.upload.maxUploadSize"));
        if (file != null) { //判断request是否有文件上传
            if(file.getSize()>maxSize){
                throw new MaxUploadSizeExceededException(maxSize);
            }
            FileModel fileModel = null;
            fileModel = new FileModel();
            Long userId = ContextUtils.getUserId();
            Long createdOrg = ContextUtils.getUserOrgId();

            //文件名称随机生成
            String uuid = UUID.randomUUID().toString();
            String fileName = file.getOriginalFilename();
            fileName = fileName.substring(0,fileName.lastIndexOf("."))+"_"+uuid + fileName.substring(fileName.lastIndexOf("."));
            long size = file.getSize();
            String contentType = file.getContentType();
            //服务器上传路径
            String dir= RuntimeEnvironmentUtil.getValue("lpfx.upload", "lpfx.upload.filepath");
            File localFile = new File(dir+"/" + fileName);
            //本地路径
           // File localFile = new File("e:/files/" + fileName);

            file.transferTo(localFile); //将上传文件写到服务器上指定的文件
            //保存信息到数据库
            fileModel.setFileName(file.getOriginalFilename());
      //     fileModel.setFilePath("e:/files/" + fileName);
            fileModel.setFilePath(dir+"/"+ fileName);
            fileModel.setFileDesc(fileDesc);
            fileModel.setModuleId(moduleId);
            fileModel.setCreatedOrg(createdOrg);
            fileModel.setCreatedBy(userId);
            fileModel.setUpdatedBy(userId);
            fileModel.setCreatedDate(new Date());
            fileModel.setUpdatedDate(new Date());
            String sizeStr = DataUtil.byteChange(size);
            fileModel.setFileSize(sizeStr);
            fileService.saveFile(fileModel);
        }
        return ReturnUtils.getSuccessResult(null);

    }
View Code

 

posted @ 2016-11-14 14:55  凡——凡  阅读(219)  评论(0)    收藏  举报