在企业应用的快速开发中,咱们须要尽快的完成一些功能。若是您使用了Ant Design Vue,在进行表单的文件上传相关功能开发的时候,您确定火烧眉毛地须要找到一篇包治百病的文章,正是如此,才有了该文的诞生,愿以此文解君忧。javascript
为了让各位看官老爷们便于理解,直接上代码,但愿能将整件事说明白。html
<a-form :form="form"> <a-form-item label="名称" style="margin-bottom: 0;"> <a-input v-decorator="['name', {rules: [{required: true, message: '请输入名称!'}]}]" /> </a-form-item> <a-form-item> <a-upload :multiple="true" :fileList="downloadFiles" :remove="handleDownloadFileRemove" :customRequest="downloadFilesCustomRequest" > <a-button class="upload-btn"> <a-icon type="upload" > 相关下载 </a-button> </a-upload> </a-form-item> </a-form>
const dibootApi = { get (url, params) { return axios.get(url, { params }) }, upload(url, formData) { return service({ url, method: 'POST', data: formData }) } } export default dibootApi
export default { name: 'demoForm', data () { title: '新建', // 该表单的功能标题 form: this.$form.createForm(this), // 表单数据初始化,没什么好说的 model: {}, // 若是是更新表单,以前的数据放到这里,来作数据初始化显示之用 downloadFiles: [] // 已经上传的文件列表 }, methods: { // 初始打开的表单时的处理(若是是更新表单,这里首先须要读取出相关数据) async open (id) { if (id === undefined) { // 没有id数据则认为是新建 this.model = {} this.afterOpen() } else { // 不然做为更新处理 const res = await dibootApi.get(`/${this.name}/${id}`) if (res.code === 0) { this.model = res.data this.title = '编辑' this.afterOpen(id) } else { this.$notification.error({ message: '获取数据失败', description: res.msg }) } } }, // 更新表单在读取数据完成后的操做 afterOpen (id) { // 获取该记录信息后,回显文件列表相关操做 dibootApi.post(`/demo/getFiles/${id}`).then(res => { if (res.code === 0){ if (res.data.downloadFile !== undefined){ res.data.downloadFile.forEach(data => { this.downloadFiles.push(this.fileFormatter(data)) }) } } }) }, // 重写a-upload的文件上传处理方式 downloadFilesCustomRequest (data) { this.saveFile(data) }, // 上传并保存文件 saveFile (data){ const formData = new FormData() formData.append('file', data.file) dibootApi.upload('/demo/upload', formData).then((res) => { if (res.code === 0){ let file = this.fileFormatter(res.data) // 上传单个文件后,将该文件会先到a-upload组件的已上传文件列表中的操做 this.downloadFiles.push(file) } else { this.$message.error(res.msg) } }) }, // 对上传成功返回的数据进行格式化处理,格式化a-upload能显示在已上传列表中的格式(这个格式官方文档有给出的) fileFormatter(data) { let file = { uid: data.uuid, // 文件惟一标识,建议设置为负数,防止和内部产生的 id 冲突 name: data.name, // 文件名 status: 'done', // 状态有:uploading done error removed response: '{"status": "success"}', // 服务端响应内容 } return file }, // 没错,删除某个已上传的文件的时候,就是调用的这里 handleDownloadFileRemove (file) { const index = this.downloadFiles.indexOf(file) const newFileList = this.downloadFiles.slice() newFileList.splice(index, 1) this.downloadFiles = newFileList }, // 表单校验就靠他了,不过这里面仍是能够对须要提交的一些数据作些手脚的 validate () { return new Promise((resolve, reject) => { this.form.validateFields((err, fieldsValue) => { if (!err) { // 设置上传文件列表 const downloadFiles = this.downloadFiles.map(o => { return o.uid }) const values = { ...fieldsValue, 'downloadFiles': downloadFiles } resolve(values) } else { reject(err) } }) }) }, // 表单提交的相关操做 async onSubmit () { const values = await this.validate() try { let result = {} if (this.model.id === undefined) { // 新增该记录 result = await this.add(values) } else { // 更新该记录 values['id'] = this.model.id result = await this.update(values) } // 执行提交成功的一系列后续操做 this.submitSuccess(result) } catch (e) { // 执行提交失败的一系列后续操做 this.submitFailed(e) } }, // 新增数据的操做 async add (values) { .... }, // 更新数据的操做 async update (values) { ... } } }
/*** * 获取文件信息列表 * @param id * @return * @throws Exception */ @PostMapping("/getFiles/{id}") public JsonResult getFilesMap(@PathVariable("id") Serializable id) throws Exception{ List<File> files = fileService.getEntityList( Wrappers.<File>lambdaQuery() .eq(File::getRelObjType, Demo.class.getSimpleName()) .eq(File::getRelObjId, id) ); return new JsonResult(Status.OK, files); } /*** * 上传文件 * @param file * @param request * @return * @throws Exception */ @PostMapping("/upload") public JsonResult upload(@RequestParam("file") MultipartFile file) throws Exception { File fileEntity = demoService.uploadFile(file); return new JsonResult(Status.OK, fileEntity, "上传文件成功"); } /*** * 建立成功后的相关处理 * @param entity * @return */ @Override protected String afterCreated(BaseEntity entity) throws Exception { DemoDTO demoDTO = (DemoDTO) entity; // 更新文件关联信息 demoService.updateFiles(new ArrayList<String>(){{ addAll(demoDTO.getDownloadFiles()); }}, demoDTO.getId(), true); return null; } /*** * 更新成功后的相关处理 * @param entity * @return */ @Override protected String afterUpdated(BaseEntity entity) throws Exception { DemoDTO demoDTO = (DemoDTO) entity; // 更新文件关联信息 demoService.updateFiles(new ArrayList<String>(){{ addAll(demoDTO.getDownloadFiles()); }}, demoDTO.getId(), false); return null; }
@Override public File uploadFile(MultipartFile file) { if(V.isEmpty(file)){ throw new BusinessException(Status.FAIL_OPERATION, "请上传图片"); } String fileName = file.getOriginalFilename(); String ext = fileName.substring(fileName.lastIndexOf(".")+1); String newFileName = S.newUuid() + "." + ext; //TODO: 须要对合法的文件类型进行验证 if(FileHelper.isImage(ext)){ throw new BusinessException(Status.FAIL_OPERATION, "请上传合法的文件类型"); }; // 说明:此处为咱们的处理流程,看官们须要根据本身的需求来对文件进行保存及处理(以后咱们的File组件开源以后也能够按照此处的处理) String filePath = FileHelper.saveFile(file, newFileName); if(V.isEmpty(filePath)){ throw new BusinessException(Status.FAIL_OPERATION, "图片上传失败"); } File fileEntity = new File(); fileEntity.setRelObjType(Demo.class.getSimpleName()); fileEntity.setFileType(ext); fileEntity.setName(fileName); fileEntity.setPath(filePath); String link = "/file/download/" + D.getYearMonth() + "_" + newFileName; fileEntity.setLink(link); boolean success = fileService.createEntity(fileEntity); if (!success){ throw new BusinessException(Status.FAIL_OPERATION, "上传文件失败"); } return fileEntity; } @Override public void updateFiles(List<String> uuids, Long currentId, boolean isCreate) { // 若是不是建立,须要删除不在列表中的file记录 if (!isCreate){ fileService.deleteEntities(Wrappers.<File>lambdaQuery().notIn(File::getUuid, uuids)); } // 进行相关更新 boolean success = fileService.updateEntity( Wrappers.<File>lambdaUpdate() .in(File::getUuid, uuids) .set(File::getRelObjType, Demo.class.getSimpleName()) .set(File::getRelObjId, currentId)); if (!success){ throw new BusinessException(Status.FAIL_OPERATION, "更新文件信息失败"); } }