前端:
<!--<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);
}
}