.net core3.1 webapi + vue + element-ui upload組件實現文件上傳

首先,先看我我的的項目結構。html

 

 

 這個webapi項目是專門做爲圖片上傳的業務處理,而其中分爲兩個控制器:單圖片上傳和多圖片上傳。在接下來的內容主要仍是針對單文件上傳,對於多文件的上傳,我暫且還沒有研究成功。前端

其中pictureoptions類,因爲我把關於圖片上傳相關的配置項(保存路徑、限制的文件類型和大小)寫在了配置文件中,因此接下來會經過依賴注入的方式,注入到這個類中vue

 

接下來,正式開工web

第一步,配置文件的設置

 

"PictureOptions": {
"FileTypes": ".gif,.jpg,.jpeg,.png,.bmp,.GIF,.JPG,.JPEG,.PNG,.BMP",
"MaxSize": 10485760,
"ImageBaseUrl": "G:\\dotnet\\imageServer\\evaluate"
}

而後在項目根目錄下新建PictureOptions類element-ui

 1     public class PictureOptions
 2     {
 3         /// <summary>
 4         /// 容許的文件類型
 5         /// </summary>
 6         public string FileTypes { get; set; }
 7         /// <summary>
 8         /// 最大文件大小
 9         /// </summary>
10         public int MaxSize { get; set; }
11         /// <summary>
12         /// 圖片的基地址
13         /// </summary>
14         public string ImageBaseUrl { get; set; }
15     }

 

第二步,依賴注入

1 services.Configure<PictureOptions>(Configuration.GetSection("PictureOptions"));
後端

在SingleImageUploadController中構造注入

 

 這裏要注意,你要把Cors跨域配置好,關於跨域,能夠前往閱讀個人另外一篇博文api

第三步,構建POST api

在element-ui中關於upload組件的api說明文檔,能夠發現一個很是重要的信息跨域

 

 

 

 upload組件他實際是經過提交form表單的方式去請求url服務器

因此,後臺這邊,咱們也是要經過form表單,獲取上傳的文件,具體代碼以下:

 

 1         /// <summary>
 2         /// 上傳文件
 3         /// </summary>
 4         /// <param name="file">來自form表單的文件信息</param>
 5         /// <returns></returns>
 6         [HttpPost]
 7         public IActionResult Post([FromForm] IFormFile file)
 8         {
 9             if (file.Length <= this._pictureOptions.MaxSize)//檢查文件大小
10             {
11                 var suffix = Path.GetExtension(file.FileName);//提取上傳的文件文件後綴
12                 if (this._pictureOptions.FileTypes.IndexOf(suffix) >= 0)//檢查文件格式
13                 {
14                     CombineIdHelper combineId = new CombineIdHelper();//我本身的combine id生成器
15                     using (FileStream fs = System.IO.File.Create($@"{this._pictureOptions.ImageBaseUrl}\{combineId.CreateId()}{suffix}"))//注意路徑裏面最好不要有中文
16                     {
17                         file.CopyTo(fs);//將上傳的文件文件流,複製到fs中
18                         fs.Flush();//清空文件流
19                     }
20                     return StatusCode(200, new { newFileName = $"{combineId.LastId}{suffix}" });//將新文件文件名回傳給前端
21                 }
22                 else
23                     return StatusCode(415, new { msg = "不支持此文件類型" });//類型不正確
24             }
25             else
26                 return StatusCode(413, new { msg = $"文件大小不得超過{this._pictureOptions.MaxSize / (1024f * 1024f)}M" });//請求體過大,文件大小超標
27         }

第四步,配置前端vue項目

 1         <el-upload
 2           action="http://192.168.43.73:5008/api/SingleImageUpload"
 3           list-type="picture-card"
 4           :on-preview="handlePictureCardPreview"
 5           :on-remove="handleRemove"
 6           :on-success="handleUploadSuccess"
 7           :on-error="handleUploadError"
 8         >
 9           <i class="el-icon-plus"></i>
10         </el-upload>
11         <el-dialog :visible.sync="dialogVisible">
12           <img width="100%" :src="dialogImageUrl" alt />
13         </el-dialog>

而後是methodui

 1   data () {
 2     return {
 3       dialogImageUrl: '',
 4       dialogVisible: false,
 5       images: []
 6     }
 7   },
 8   methods: {
 9     handleRemove (file, fileList) {
10       this.images.forEach((element, index, arr) => {
11         if (file.name === element.oldFile.name) {
12           arr.splice(index, 1)
13         }
14       })
15       console.log(this.images)
16     },
17     handlePictureCardPreview (file) {
18       this.dialogImageUrl = file.url
19       this.dialogVisible = true
20     },
21     handleUploadSuccess (response, file, fileList) {
22       console.log(response)
23       console.log(file)
24       console.log(fileList)
25       this.images.push({
26         newFileName: response.newFileName, // 服務器端的新文件名,即後端回調過來的數據
27         oldFile: {
28           name: file.name, // 上傳以前的文件名,客戶端的
29           url: file.url // 頁面顯示上傳的圖片的src屬性綁定用的
30         }
31       })
32     },
33     handleUploadError (response, file, fileList) {
34       this.$message.error(JSON.parse(response.message).msg)
35     }
36   }

 這裏面注意各個handle中頻繁出現的三個參數:response 、 file 和 fileList

 其中response,就是後端發送過來的數據

 file:單文件上傳時,他包含了該文件全部信息

 fileList:指的是多文件上傳所包含的文件信息

相關文章
相關標籤/搜索