簡介
使用後臺,搭建後臺功能,非常必要的功能就是上傳功能,那麼結合NCF如何使用表單上傳呢,下面讓我來介紹一下哈
資源
element-ui upload:https://element.eleme.io/#/zh-CN/component/upload#methods
vue 方法:https://cn.vuejs.org/v2/guide/events.html#%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86%E6%96%B9%E6%B3%95
步驟
1.在頁面表單中加入上傳控件
2.在js頁面中加入處理上傳的邏輯方法
3.服務端來處理接收到的文件信息
3-1.通過後臺本身的.cs文件來處理接受文件
3-2.通過接口來上傳文件(本文介紹的)
實施
1.在表單中(即在xxx.cshtml文件中)添加element ui 中的 el-upload 控件,代碼如下
<el-form-item label="封面圖"> <el-upload action="https://localhost:44311/api/v1/common/upload"
list-type="picture-card"
show-file-list="true"
accept="image/png, image/jpeg"
:on-success="uploadSuccess"
:on-error="uploadError"
:on-preview="handlePictureCardPreview"
:on-remove="handleRemove">
<i class="el-icon-plus"></i>
<div class="el-upload__tip" slot="tip">不能超過100MB</div>
</el-upload>
<img width="100%" :src="dialogImageUrl" alt="">
<el-input class="hidden" v-model="dialog.data.cover" clearable placeholder="封面圖" />
</el-form-item>
2.在js文件中增加處理上傳控件的邏輯方法
handleRemove(file, fileList) { console.log(file, fileList); }, handlePictureCardPreview(file) { this.dialogImageUrl = file.url; this.dialogVisible = true; }, uploadSuccess(res, file, fileList) { // 上傳成功 this.fileList = fileList; console.log("上傳成功" + fileList.length); console.log(JSON.stringify(res)); if (res.code == 200) { this.$notify({ title: '成功', message: '恭喜你,上傳成功', type: 'success' }); this.dialog.data.cover = res.data; } else { this.$notify.error({ title: '失敗', message: '上傳失敗,請重新上傳' }); } }, uploadError() { //this.refs.upload.clearFiles(); this.$notify.error({ title: '失敗', message: '上傳失敗,請重新上傳' }); },
3.服務端接口接收文件的方法
/// <summary> /// 上傳文件 /// </summary> /// <param name="file">文件信息</param> /// <returns></returns> [HttpPost] public IActionResult Upload([FromForm] IFormFile file) { string prefixPath = string.Empty; try { var file_data = this.Request.Form.Files[0]; if (file_data == null) { return Fail("文件參數無效,請提供name值爲file_data的文件"); } //驗證文件擴展名 var extension = Path.GetExtension(file_data.FileName); if (!AllowFileExtension.FileExtension.Contains(extension)) { return Fail("不支持此擴展名文件的上傳!"); } //基礎存儲路徑 var basePath = "default"; // sysKeyModel.Name; //驗證文件前綴路徑有效性 if (!string.IsNullOrWhiteSpace(prefixPath)) { if (prefixPath.IndexOfAny(Path.GetInvalidPathChars()) > -1)//驗證路徑有效性 { return Fail("無效路徑!"); } //進一步規範路徑 var invalidPattern = new Regex(@"[\\\/\:\*\?\042\<\>\|]"); prefixPath = invalidPattern.Replace(prefixPath, ""); prefixPath = prefixPath.Replace("_", "\\");//使用下劃線“_”代替斜槓“\” basePath = Path.Combine(basePath, prefixPath); } //物理文件路徑 var pathMp = Path.Combine(_webHostEnvironment.ContentRootPath, staticResourceSetting.CurrentValue.RootDir, basePath); if (!Directory.Exists(pathMp)) Directory.CreateDirectory(pathMp); string strFileName = file_data.FileName.Split('\\').LastOrDefault(); var filename = $"{DateTime.Now:yyyyMMddHHmmss}-{UniqueHelper.LongId()}{extension}"; string strFileHash = string.Empty; string strFilePath = string.Empty; using (var fs = new FileStream(Path.Combine(pathMp, filename), FileMode.CreateNew)) { file_data.CopyTo(fs); strFileHash = HashHelper.SHA1File(fs);//賦值文件Hash值 fs.Flush(); } ////物理文件路徑(斜槓)轉換爲URL路徑(反斜槓) strFilePath = $"https://localhost:44311/static/default/{filename}"; return Success(strFilePath); } catch (Exception ex) { return Fail(ex.Message); } }
如果你已經動手走到這裏了,那麼恭喜你,你完成上傳功能了。
不清楚的地方,再問我
關注我的博客,瞭解更多NCF的實用功能