周尚緯
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
      • No invitee
    • Publish Note

      Publish Note

      Everyone on the web can find and read all notes of this public team.
      Once published, notes can be searched and viewed by anyone online.
      See published notes
      Please check the box to agree to the Community Guidelines.
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
No invitee
Publish Note

Publish Note

Everyone on the web can find and read all notes of this public team.
Once published, notes can be searched and viewed by anyone online.
See published notes
Please check the box to agree to the Community Guidelines.
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# 在 ASP.NET Core MVC 使用 HTML5 實現多檔案上傳 [![hackmd-github-sync-badge](https://hackmd.io/dkm8rmnTQ_-st6DhboFJdg/badge)](https://hackmd.io/dkm8rmnTQ_-st6DhboFJdg) ## 使用版本 .NET 6 vue@2.7.10 axios@0.27.2 bootstrap@5.2.1 popper.js@2.11.6 ## 實作前需了解內容 ### HTML * [FormData](https://docs.w3cub.com/dom/formdata/using_formdata_objects) 使用 XMLHttpRequest 時,可以用 FormData 設定 Key/Value 的資料傳送. 它主要用於發送表單數據。 * [multipart/form-data](https://www.w3schools.com/tags/att_form_enctype.asp) 表單上傳檔案時 form 的「enctype」屬性或是 ajax headers 裡「Content-Type」必需設置此值,不過如果 ajax 上傳檔案是使用 FormData,瀏覽器會自動添加,所以一般不用也不建議特別設定。 * [HTML <input> multiple Attribute](https://www.w3schools.com/tags/att_input_multiple.asp) 簡單屬性,使用 multiple 屬性可以讓 input file 選擇多個檔案,簡單屬性標準寫法以 multiple 為例,`multiple="multiple"`,但實際寫`multiple`或`multiple="{任意值}"`皆是同樣效果。 ```htmlmixed <input type="file" id="files" name="files" multiple="multiple" /> ``` * [Progress Event Handler](https://docs.w3cub.com/dom/xmlhttprequest/progress_event) XMLHttpRequest 會在接收到更多資料時,定時觸發的事件,其中 Event Args 有兩個[屬性](https://www.w3schools.com/jsref/obj_progressevent.asp)可用於繪製 Progress Bar。 * loaded:已加載的資料量。 * tota:需加載的總資料量。 ### .NET * [IFormFile](https://learn.microsoft.com/zh-tw/dotnet/api/microsoft.aspnetcore.http.iformfile?view=aspnetcore-6.0) 過往在 MVC 5 時,檔案上傳一直無法與模型繫結屬性整合在一起,必須在 Action 使用「HttpPostedFileBase」型別的參數,或是使用「Request.Files」來取得上傳檔案資料。 ASP.NET Core 增加了「IFormFile」型別可來做為檔案上傳時的繫結屬性型別,多檔案上傳則使用「IFormFileCollection 」。 ## 實際範例 HTML ```htmlmixed <div id="app"> <input type="file" multiple="multiple" asp-for="Files" v-on:change="handleFileChange" /> <div class="progress" v-show="progressBarValue > 0"> <div class="progress-bar" role="progressbar" :style="{ width: progressBarValue + '%' }" v-bind:aria-valuenow="{progressBarValue}" aria-valuemin="0" aria-valuemax="100">{{ progressBarValue }}%</div> </div> <button class="btn-primary" type="button" v-on:click="handleSubmit">送出</button> </div> ``` JavaScript ```javascript new Vue({ el: '#app', data: { formData: new FormData, progressBarValue: 0 }, methods: { handleFileChange(e) { this.formData = new FormData(); for (let i = 0; i < e.target.files.length; i++) { this.formData.append(e.target.id, e.target.files[i]); } }, handleSubmit() { let config = { // axios會使用它作為XMLHttpRequest的Progress Event onUploadProgress: progressEvent => { this.progressBarValue = (progressEvent.loaded / progressEvent.total * 100 | 0); } }; axios.post('@Url.Action("Index3")', this.formData, config).then(response => { alert(response.data.message); }).catch(thrown => { alert(thrown); }); } } }); ``` ViewModel ``` public class IndexViewModel { [DisplayName("上傳檔案")] [Required] public IFormFileCollection Files { get; set; } } ``` Controller ```csharp [HttpPost] public async Task<IActionResult> Index3(IndexViewModel viewModel) { if (!ModelState.IsValid) { string message = ModelState.First(x => x.Value.Errors.Count > 0) .Value?.Errors.FirstOrDefault()?.ErrorMessage; return Ok(new { Message = message }); } foreach (var formFile in viewModel.Files) { if (formFile.Length > 0) { // 請替換實際存放位置 var filePath = Path.GetTempFileName(); using var stream = System.IO.File.Create(filePath); await formFile.CopyToAsync(stream); } } return Ok(new { Message = "上傳成功" }); } ``` ## 檔案上傳大小限制 因為資安因素,Request 和 Response 等都會有大小限制,而檔案上傳時,會牽涉到的兩個屬性主要為 MultipartBodyLengthLimit 和 MaxRequestBodySize,如果要從程式端調整限制有以下作法: * Global設定 ```csharp // Program.cs builder.Services.Configure<FormOptions>(x => { // multipart body的最大長度限制,預設約128MB x.MultipartBodyLengthLimit = long.MaxValue; }); // 利用Kestrel部署的應用配置Request的大小限制 builder.WebHost.ConfigureKestrel(opt => { opt.Limits.MaxRequestBodySize = long.MaxValue; }); // 利用IIS部署的應用配置Request的大小限制 builder.Services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = long.MaxValue; }); ``` * 從Attribute限制 ``` [HttpPost] [DisableRequestSizeLimit] [RequestSizeLimit(long.MinValue)] // 與DisableRequestSizeLimitAttrubute二擇一使用 [RequestFormLimits(MultipartBodyLengthLimit = long.MaxValue)] public async Task<IActionResult> Index(IndexViewModel viewModel) { //... } ``` ::: danger 注意事項 * 設定 `long.MaxValue` 只是舉例用,請依照實際需求設置限制大小。 * 上述設定單位皆為 byte。 * Attribute 優先度會高於 Global 設定。 ::: ###### tags: `.NET` `.NET Core & .NET 5+` `ASP.NET Core` `axios`

Import from clipboard

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Upgrade to Prime

  • Edit verison name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare with
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Upgrade

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Upgrade

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully