需求1:前端提交表单时附件跟着一起发送给后台
需求2:前台获取后台附件
我这里并没有使用扩展组件,都是官方API
//前端代码
上传附件
//显示图片名称 currentFilesPath-数组文件/单个文件 、previewFile-预览文件
{{(index + 1) + '、' + file.name}} //图标,可有可无,我这个图标含义是删除对文件。
选择文件
openFile() {uni.chooseFile({count: 10,//选择文件个数,默认100extension: ['.doc', '.ppt','.xls', '.pdf', 'docx', '.jpg', '.png', '.jpeg','text'],//可选择文件类型// type: 'all',//支持所有类型文件success: (res) => { //res == 选择文件本地临时文件路径列表//遍历多图片,并将每个图片有用信息提取出来,设置为一个对象res.tempFilePaths.forEach((item, index) => {this.currentFilesPath.push(res.tempFiles[index++])//页面显示文件名称let tmp = {};tmp.name = 'files';tmp.uri = item;this.tempFile.push(tmp)//将temFile数组数据发给后台})}});},
发生数据
doSave(){//点击提交按钮,触发该函数uni.uploadFile({//会自动执行url: 'xxxxx',//后台结束数据路径files: this.tempFile,//需要上传文件数据name: 'files',header: {'content-type':'multipart/form-data; boundary=----WebKitFormBoundaryHEdN1AIjcdUkAaXM',},formData: {//"data": JSON.stringify(postData)//"data":表单数据},success: (res) => {//成功提交},fail: (err) => {//提交失败}});}
后台代码
@RequestMapping(value = "xxxxx", method = {RequestMethod.POST})@ApiOperation(value = "", notes = "", httpMethod = "POST")public SuccessResponse confirm(HttpServletRequest request) {//获取前端上传的文件+表单List multipartFiles = ((MultipartHttpServletRequest) request).getFiles("files");//文件数据String khTsData = request.getParameter("data");//表单数据,还需要将这个字符串转为对象。}
预览后台文件-前台代码
previewFile(savePath, type) {let fileType = ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'];var file = [];let filePath = 'xxxxx‘ //后台获取文件流的地址file.push(imgepath);//if (!fileType.includes(type)) { //不包含 fileType类型,所以预览其他类型文件uni.previewImage({//预览图片API方法urls: file,//*主要这个地址是文件资源地址,并不是文件临时地址*,,只接受数组longPressActions: { //获取带图片长按图片显示操作菜单,默认保存itemList: ['发送给朋友', '保存图片', '收藏'],success: function(data) {console.log('加载成功')},fail: function(err) {console.log(err.errMsg);}}});}else{uni.downloadFile({//预览包含fileType文件url: img,success: (res) => {if (res.statusCode === 200) {uni.openDocument({filePath: res.tempFilePath,success: function(res) {console.log('打开成功');}});}}});}
后台获取文件流
@ControllerLogExeTime(description = "下载文件", log = false)@RequestMapping(value = "**xxxxx", method = { RequestMethod.GET })@ApiOperation(value = "下载文件", httpMethod = "GET")@ApiImplicitParams({})@ResponseBodypublic void download(HttpServletRequest request, HttpServletResponse response) throws IOException {//返回一个文件流给浏览器,然后浏览器自己会将这个文件流转为文件}