uni文件上传及后台获取文件
admin
2024-02-17 10:12:21

需求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 {//返回一个文件流给浏览器,然后浏览器自己会将这个文件流转为文件}

相关内容

热门资讯

上海旅游节大巡游花车阵容抢先看... 2026上海旅游节大巡游9月12日外滩启幕,21辆全新主题花车携手21支境内外表演方队联袂登场,邀你...
原创 8... 上周门诊来了位 62 岁的张阿姨,得糖尿病快五年了,平时管嘴特别严,糖果、点心、甜饮料一概不碰,连水...
原创 餐... 2026年9月8日晚,南京浦口区泰冯路29号,墨语江南·阿婆菜餐厅户外帐篷里,灯火温润,其间还天降喜...
原创 它... 人到中年肝肾精血慢慢耗损,容易腰膝酸软、头晕眼花、精神疲惫。黄精性平,擅长补肝肾、益精血,搭配不同食...
同样卖奶茶,为何古茗赚了15亿... 出品/联商专栏 撰文/老刀 编辑/蔡建桢 今年上半年,蜜雪、古茗、霸王茶姬、茶百道、沪上阿姨全部盈利...