在使用若依的框架时,发现若依移动端框架中已经封装好了一个upload.js用于文件上传,自己在这个版本的基础上稍作改动,成功实现文件上传功能

若依公共的 upload.js 

import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

let timeout = 10000
const baseUrl = config.baseUrl

const upload = config => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  config.header = config.header || {}
  if (getToken() && !isToken) {
    config.header['Authorization'] = 'Bearer ' + getToken()
  }
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params)
    url = url.slice(0, -1)
    config.url = url
  }
  return new Promise((resolve, reject) => {
      uni.uploadFile({
        timeout: config.timeout || timeout,
		url: baseUrl + config.url,
        filePath: config.data,
        name: config.name || 'file',
        header: config.header,
        formData: config.formData,
        success: (res) => {
          let result = JSON.parse(res.data)
          const code = result.code || 200
          const msg = errorCode[code] || result.msg || errorCode['default']
          if (code === 200) {
            resolve(result)
          } else if (code == 401) {
            showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
              if (res.confirm) {
                store.dispatch('LogOut').then(res => {
                  uni.reLaunch({ url: '/pages/login/login' })
                })
              }
            })
            reject('无效的会话,或者会话已过期,请重新登录。')
          } else if (code === 500) {
            toast(msg)
            reject('500')
          } else if (code !== 200) {
            toast(msg)
            reject(code)
          }
        },
        fail: (error) => {
					console.log("error", error);
          let { message } = error
          if (message == 'Network Error') {
            message = '后端接口连接异常'
          } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
          } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
          }
          toast(message)
          reject(error)
        }
      })
  })
}

export default upload

自己再封装一个 js 文件,此处命名 upload.js 但不和若依的文件放在同一个目录下

import upload from '@/utils/upload.js'

export function uploadFile(data) {
  return upload({
    url: '/common/upload',
    method: 'post',
    data: data
  })
}

在文件中调用需要先引入

import { uploadFile } from '@/api/common/upload.js'

再在 uni.chooseImage 中调用

selectPic() {
    var _this = this
	uni.chooseImage({
	    count: 1, //默认9
		sizeType: 'compressed', //可以指定是原图还是压缩图,默认二者都有
		sourceType: ['album'], //从相册选择
		success: function(res) {
			uploadFile(res.tempFilePaths[0]).then(fileRes => {
				console.log(fileRes);
				fileRes = JSON.parse(fileRes)
				uni.showToast({
					title: "图片上传成功,保存生效",
					icon: "none"
				})
			});
		}
	});
},

controller 代码

/**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐