.net core ,不用[frombady],不然会识别为string类型(swagger测试)
[ApiController]
public class ImageController : ControllerBase
{
[HttpPost]
public IActionResult UploadImage(IFormFile file)
{
return Ok("ok");
}
}
前端element
action必填,但是又涉及到跨域问题,直接用另外一个属性before-upload赋值一个方法上传
<template>
<div class="BlogEdit">
<el-upload
class="upload-demo"
ref="upload"
action="123"
:before-upload="upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false"
>
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button
style="margin-left: 10px"
size="small"
type="success"
@click="submitUpload"
>上传图片</el-button
>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过500kb
</div>
</el-upload>
</div>
</template>
JS代码,文件上传的请求应该是form格式,因此new一个formdata,this.http.uploadFile是简单封装的axios,可直接替换
data() {
return {
fileList: []
};
},
methods: {
submitUpload() {
this.$refs.upload.submit();
},
handleRemove(file, fileList) {
console.log(file, fileList);
this.fileList = fileList;
},
handlePreview(file) {
console.log(file);
},
upload(file) {
let fd = new FormData();
fd.append('file', file);
this.http.uploadFile('Image/UploadImage', fd).then((res) => {
console.log(res);
});
}
}
axios修改请求头的content-type
function uploadFile (url, param) {
console.log(param)
return new Promise((resolve, reject) => {
axios.post(url, param, { headers: { 'Content-Type': 'multipart/form-data' } })
.then(response => {
resolve(response.data)
})
.catch((error) => {
console.log(error)
reject(error.data)
})
})
}
效果