[asp.net mvc][jquery]簡易實做檔案上傳
.cshtml:
其實就是用input type = 'file'
<input type="file" id="fileUpload">
<button class="btn btn-success" id="btnSave" onclick="SaveMeeting()">儲存</button>
<input type="hidden" id="hidAppPath" value="@Url.Content("~/")" />
<!--應用程式根目錄路徑-->
javascript+jquery:
function SaveMeeting() {
var formJSON = {};
var fileContent = $('#fileUpload').get(0).files[0];
var reader = new FileReader();
reader.readAsDataURL(fileContent);
reader.onload = function () {
console.log(reader.result);
formJSON = {
TestParam: 'aabbcc',
FileContentBase64: reader.result,
};
SaveMeetingPost(formJSON);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
function SaveMeetingPost(formJSON) {
var appPath = $("#hidAppPath").val();
console.log('送出之前顯示:');
console.log(formJSON);
$.ajax({
type: 'POST',
url: appPath + 'Admin/SaveMeetingPost/',
data: formJSON,
//這是回傳多筆JSON資料的情況
success: function (resultData) {
if (resultData.IsSuccess == true) {
alert('存檔成功!');
}
else {
console.log(resultData.ErrorMsg);
alert('出現意料之外的錯誤,請查看F12的writeLog()紀錄。');
}
},
error: function (error) {
console.log(error);
alert('出現意料之外的錯誤,請查看F12的writeLog()紀錄。');
},
});
}
Controller的c#程式碼:
[HttpPost]
//存檔
public ActionResult SaveMeetingPost(AdminMeetingModalPostModel model)
{
if (model == null)
{
return Json(new EmptyResult());
}
AdminMeetingSaveResultModel result = new AdminMeetingSaveResultModel();
try
{
if (model.FileContentBase64.Length > 0)
{
string _FileName = Path.GetFileName("temp.txt");
string _path = Path.Combine(Server.MapPath("~/Content/pdf/"), _FileName);
Byte[] bytes = Convert.FromBase64String(model.FileContentBase64.Split(',')[1]);
System.IO.File.WriteAllBytes(_path, bytes);
}
result.IsSuccess = true;
result.InfoMsg = "上傳成功";
}
catch(Exception ex)
{
result.IsSuccess = false;
result.ErrorMsg = ex.ToString();
}
//回傳Json資料
return Json(result);
}
Model的c#類別:
public class AdminMeetingModalPostModel
{
public string CompanyCode { get; set; }
public string MeetingCode { get; set; }
public int Year { get; set; }
public int Seq { get; set; }
public string FileContentBase64 { get; set; }
}
public class AdminMeetingSaveResultModel
{
public bool IsSuccess { get; set; } = false;
public string ErrorMsg { get; set; } = string.Empty;
public string InfoMsg { get; set; } = string.Empty;
}
執行結果:


這篇大概是這樣……
ps.補充:如果是大型檔案上傳,請在web.config加入以下的maxRequestLength屬性,這邊的範例可以讓你上傳1G大小左右的檔案:
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" maxRequestLength="1048576" />
<customErrors mode="Off"/>
</system.web>
參考資料:
Upload Files In ASP.NET MVC 5 (c-sharpcorner.com)
在網頁應用程式中使用本地檔案 - Web APIs | MDN (mozilla.org)