前后端分離項目,數(shù)據(jù)交互都知道怎么做,文件上傳應該也都知道。但是存在有些情況下,我們需要將文件和數(shù)據(jù)同時提交。ElementPlus的upload上傳組件提供了可攜帶數(shù)據(jù)的data屬性,但是在.NetWebApi下應該如何做接收呢?下面通過示例我們簡單實現(xiàn)一下。開發(fā)環(huán)境:.NET 6
開發(fā)工具:Visual Studio 2022
- 這里假設我們已經有了一個Vue3項目,并且引入了ElementPlus。
- 首先是前端的html代碼,這里我們需要同時將數(shù)據(jù)內容和文件上傳到后臺,如下:
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
<el-form-item label="數(shù)據(jù)內容" prop="Value">
<el-input v-model="formData.Value" :autosize="{ minRows: 8, maxRows: 16 }" type="textarea" clearable></el-input>
</el-form-item>
</el-col>
<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
<el-form-item label="選擇文件" prop="Name">
<el-input v-model="formData.Name" readonly>
<template #append>
<el-upload
ref="uploadRef"
:action="upload.action"
:headers="upload.headers"
:show-file-list="false"
:on-change="onUploadChange"
:before-upload="onUploadBefore"
:on-success="onUploadSuccess"
:on-error="onUploadError"
:auto-upload="false"
:data="formData"
accept=".txt"
>
<el-button type="primary">選擇文件</el-button>
</el-upload>
</template>
</el-input>
</el-form-item>
</el-col>
const uploadRef = ref<UploadInstance>();
const formData = ref({
Name: '',
Value: '',
});
const onUploadChange = (file: any) => {
formData.value.Name = file.name;
};
const onUploadBefore = (file: any) => {
if (file.name.lastIndexOf('.txt') != file.name.length - 4) {
EMsg.error('請選擇文本文件');
return false;
}
return true;
};
const onUploadSuccess = (res: any) => {
EMsg(res);
onClose();
emit('refresh');
};
const onUploadError = (res: any) => {
EMsg.error(res.Msg);
};
//提交按鈕觸發(fā)
const onSubmit = () => {
uploadRef.value!.submit();
});
};
- 上面的代碼就會在提交的時候將數(shù)據(jù)和內容直接給到WebApi,WebApi接收代碼如下:
//先定義一個接收類
public class InFileData
{
public string Name { get; set; }
public string Value { get; set; }
public IFormFile? file { get; set; }
}
[HttpPost]
public ApiJsonResult Add([FromForm] InFileData input)
{
if (input.file == null)
{
return ApiJsonResult.Convert(false,"沒有文件");
}
string filter = Path.GetExtension(input.Name);
string name = Guid.NewGuid().ToString("N") + filter;
string path = Path.Combine(App.StaticData.UploadPath, name);
using var stream = new FileStream(path, FileMode.OpenOrCreate);
input.file.CopyTo(stream);
//獲取到的表單數(shù)據(jù)
string value=input.Value;
return ApiJsonResult.Success;
}
該文章在 2024/9/18 12:26:33 編輯過