
如何快速實現REST API集成以優化業務流程
這個webapi項目是專門作為圖片上傳的業務處理,而其中分為兩個控制器:單圖片上傳和多圖片上傳。在接下來的內容主要還是針對單文件上傳,對于多文件的上傳,我暫且尚未研究成功。
其中pictureoptions類,由于我把關于圖片上傳相關的配置項(保存路徑、限制的文件類型和大小)寫在了配置文件中,所以接下來會通過依賴注入的方式,注入到這個類中
"PictureOptions": {
"FileTypes": ".gif,.jpg,.jpeg,.png,.bmp,.GIF,.JPG,.JPEG,.PNG,.BMP",
"MaxSize": 10485760,
"ImageBaseUrl": "G:\\dotnet\\imageServer\\evaluate"
}
然后在項目根目錄下新建PictureOptions類
public class PictureOptions
{
/// <summary>
/// 允許的文件類型
/// </summary>
public string FileTypes { get; set; }
/// <summary>
/// 最大文件大小
/// </summary>
public int MaxSize { get; set; }
/// <summary>
/// 圖片的基地址
/// </summary>
public string ImageBaseUrl { get; set; }
}
services.Configure<PictureOptions>
(Configuration.GetSection("PictureOptions"));
在SingleImageUploadController中構造注入
這里要注意,你要把Cors跨域配置好,關于跨域《.NET Core WebAPI + vue.js + axios 實現跨域》,可以前往閱讀我的另一篇博文
在element-ui中關于upload組件的api說明文檔,可以發現一個非常重要的信息
upload組件他實際是通過提交form表單的方式去請求url
所以,后臺這邊,我們也是要通過form表單,獲取上傳的文件,具體代碼如下:
/// <summary>
/// 上傳文件
/// </summary>
/// <param name="file">來自form表單的文件信息</param>
/// <returns></returns>
[HttpPost]
public IActionResult Post([FromForm] IFormFile file)
{
if (file.Length <= this._pictureOptions.MaxSize)//檢查文件大小
{
var suffix = Path.GetExtension(file.FileName);//提取上傳的文件文件后綴
if (this._pictureOptions.FileTypes.IndexOf(suffix) >= 0)//檢查文件格式
{
CombineIdHelper combineId = new CombineIdHelper();//我自己的combine id生成器
using (FileStream fs = System.IO.File.Create($@"{this._pictureOptions.ImageBaseUrl}\{combineId.CreateId()}{suffix}"))//注意路徑里面最好不要有中文
{
file.CopyTo(fs);//將上傳的文件文件流,復制到fs中
fs.Flush();//清空文件流
}
return StatusCode(200, new { newFileName = $"{combineId.LastId}{suffix}" });//將新文件文件名回傳給前端
}
else
return StatusCode(415, new { msg = "不支持此文件類型" });//類型不正確
}
else
return StatusCode(413, new { msg = $"文件大小不得超過{this._pictureOptions.MaxSize / (1024f * 1024f)}M" });//請求體過大,文件大小超標
}
<el-upload
action="http://192.168.43.73:5008/api/SingleImageUpload"
list-type="picture-card"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove"
:on-success="handleUploadSuccess"
:on-error="handleUploadError"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt />
</el-dialog>
然后是method
data () {
return {
dialogImageUrl: '',
dialogVisible: false,
images: []
}
},
methods: {
handleRemove (file, fileList) {
this.images.forEach((element, index, arr) => {
if (file.name === element.oldFile.name) {
arr.splice(index, 1)
}
})
console.log(this.images)
},
handlePictureCardPreview (file) {
this.dialogImageUrl = file.url
this.dialogVisible = true
},
handleUploadSuccess (response, file, fileList) {
console.log(response)
console.log(file)
console.log(fileList)
this.images.push({
newFileName: response.newFileName, // 服務器端的新文件名,即后端回調過來的數據
oldFile: {
name: file.name, // 上傳之前的文件名,客戶端的
url: file.url // 頁面顯示上傳的圖片的src屬性綁定用的
}
})
},
handleUploadError (response, file, fileList) {
this.$message.error(JSON.parse(response.message).msg)
}
}
這里面注意各個handle中頻繁出現的三個參數:response 、 file 和 fileList
其中response,就是后端發送過來的數據
file:單文件上傳時,他包含了該文件所有信息
?fileList:指的是多文件上傳所包含的文件信息
文章轉自微信公眾號@DotNet