×

vue.jsajax上传文件

vue.jsajax上传文件(vue上传文件格式)

admin admin 发表于2023-04-02 17:44:07 浏览59 评论0

抢沙发发表评论

本文目录一览:

VUE 前端大文件上传如何实现?

大文件可以切片上传,将blob进行切片。然后用ajax提交。

通常来说这种功能和VUE没有关系,原生JS实现即可

vue图片上传需要token吗

经过两个vue项目,分享一下图片上传这里的写法和注意点

1.只传一个文件信息过去时

//HTML

!-- 上传按钮 --

div class="file-upload fl-r"

span class="upload-desc"大小不能超过2M/span

a-upload

name="iFile"

accept="image/*"

:beforeUpload="beforeUpload"

:customRequest="onUpload"

:multiple="true"

:showUploadList="false"

a-button icon="cloud-upload"上传/a-button

/a-upload

/div

//JS

// 事件: 上传文件之前

beforeUpload (file, fileList) {

// 显示错误提示(防抖处理)

const showErrorMsg = debounce(this.$message.error, 20)

// 验证文件大小

const isLt1M = file.size / 1024 / 1024 2

if (!isLt1M) {

showErrorMsg('文件大小不能超出2MB')

return false

}

// 验证文件上传数量

if (fileList.length 5) {

showErrorMsg('一次上传的文件数量不能超出5个')

return false

}

return true

},

/**

* 事件: 自定义上传事件

*/

onUpload (info) {

this.isLoading = true

// 记录上传状态

this.uploading.push(true)

// 构建上传参数

var formData = new FormData()

formData.append('file', info.file)

this.$http

.post("/file/upload", formData)

.then((res) = {

// console.log("文件上传成功", res);

this.$message.success(res.msg);

if (res.code == 1) {

// 存入列表

this.fileList.push({

uid: this.fileList.length + 1,

name: res.data.name,

status: "done",

url: res.data.filePath,

});

} else {

this.$message.error(res.msg);

}

})

.catch(function (error) {

console.log(error);

});

},

以上图片上传,后端只要求传送图片信息即可(二进制),所以在vue的request拦截里面进行Content-Type修改

// 添加请求拦截器

axios.interceptors.request.use(

(config) = {

// 每次发起请求前取消掉在进行中的相同请求

removePending(config);

config.cancelToken = new cancelToken((c) = {

// 这里的ajax标识我是用请求地址请求方式拼接的字符串,当然你可以选择其他的一些方式

pending.push({ u: config.url + "" + config.method, f: c });

});

if (config.url == "/file/upload") {

config.headers["Content-Type"] = "multipart/form-data";

}

return config;

},

(error) = {

message.error("请求超时");

return Promise.reject(error);

}

);

观察控制台网络请求位置可看到一下内容,注意红圈和篮圈部分都有的

2.第二次项目中遇到,要求传文件上传token和file

起初是把只把file 自己添加到FormData()对象中了,把upload_token放在了外面,结果报错了。正确的写法就是,一起添加到formData中去。这是一个经验问题,还好是蒙对了。

vue打包后提交ajax 显示failed to load file://f:/

需要修改文件。

打开configindexjs文件,将build大于assetsPublicPath改为点加斜杠,然后找到webpackbaseconfigjs,完成后对项目进行重新打包。

Ajax是在2005年被JesseJamesGarrett提出的新术语,用来描述一种使用现有技术集合的新方法,使用Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,而不需要重载整个页面,这使得程序能够更快地回应用户的操作。-vue.jsajax上传文件