在使用若依的框架時,發(fā)現(xiàn)若依移動端框架中已經封裝好了一個upload.js用于文件上傳,自己在這個版本的基礎上稍作改動,成功實現(xiàn)文件上傳功能
若依公共的 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參數(shù)
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("登錄狀態(tài)已過期,您可以繼續(xù)留在該頁面,或者重新登錄?").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 = '系統(tǒng)接口請求超時'
} else if (message.includes('Request failed with status code')) {
message = '系統(tǒng)接口' + 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 中調用文章來源:http://www.zghlxwxcb.cn/news/detail-507034.html
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 代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-507034.html
/**
* 通用上傳請求(單個)
*/
@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());
}
}
到了這里,關于uni-app 實現(xiàn)文件上傳的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!