AmazeUI+Ajax檔案上傳,後臺.netMVC
阿新 • • 發佈:2018-11-17
前端:
<!--<link href="~/assets/css/amazeui.min.css" rel="stylesheet" />-->
<!--<script src="~/assets/js/jquery.min.js"></script>-->
<div class="am-form-group am-form-file">
<button type="button" class="am-btn am-btn-danger am-btn-sm">
<i class="am-icon-cloud-upload" ></i> 選擇要上傳的檔案</button>
<input id="doc-form-file" type="file" multiple>
</div>
<script>
$('#doc-form-file').on('change', function () {
var file = this.files[0];
var fileName = file.name;
var fileType = fileName.substr(fileName.length - 4, fileName. length);
if (fileType == '.docx' || fileType == '.doc') {
var formData = new FormData()
formData.append("file", file);
$.ajax({
url: '/Home/upLoadFile',
type: 'POST',
cache: false,
data: formData,
dataType: "json",
processData: false,
contentType: false,
success: function (json) {
//上傳成功的處理
});
} else {
alert('檔案型別不正確');
}
});
</script>
後臺:
public ActionResult upLoadFile(HttpPostedFileBase file)
{
int fileContentLength = file.ContentLength;
string filePath = Server.MapPath("~/檔案儲存目錄");
byte[] fileBytes = new byte[fileContentLength];
Stream fileStream = file.InputStream;
fileStream.Read(fileBytes, 0, fileContentLength);
string fullPath = filePath + System.IO.Path.GetFileName(file.FileName);
SaveToDisk(fileBytes, fullPath);
}
public void SaveToDisk(byte[] bytes, string saveFullPath)
{
var fullPath = Path.GetDirectoryName(saveFullPath);
//如果沒有此資料夾,則新建
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
}
//建立檔案,返回一個 FileStream,它提供對 path 中指定的檔案的讀/寫訪問。
using (FileStream stream = System.IO.File.Create(saveFullPath))
{
//將位元組陣列寫入流
stream.Write(bytes, 0, bytes.Length);
}
}