前端/C# 前后台交互文件上传、下载

时间:2021-10-11 20:59:59

试了很多方式,最终确认这个全面简单版的。废话不多说,贴码。

文件上传

input的type命名为file,即可实现文件上传。嗯~~~现在html还是很强大的。Good!

前端

单个文件上传

Html:

<form id="form1">
  <input type="file" name="files" /> 
  <input type="button" value="单文件上传" onclick="uploadFile()"/>
</form>

Jquery:

在此基础上,需要引用两个js文件:

<script src="~/Scripts/jquery-1.8.2.min.js"></script>

<script src="~/Scripts/jquery.form.js"></script>

function uploadFile() {
$("#form1").ajaxSubmit({
url: "@Url.Action("UploadFile", "Home")",  //这里也可以写成:"/Home/UploadFile",其中Home是Controller的名字;UploadFile是方法名字
type: "post",
success: function (data) {
if (data == "True" || data == true) {
}
else {
}
},
error: function (aa) {
}
});
}

多文件上传

Html:

<form enctype="multipart/form-data" id="form_example">
  <input type="file" id="files" multiple onchange="addFile()"/><br /><br />
  <input type="button" value="提交" id="submit" onclick="submitFile()" />
</form>
<div id='file-list-display'></div>

JS:

var fileList = [];

function addFile() {
var files = document.getElementById("files"),
fileListDisplay = document.getElementById('file-list-display');
for (var i = 0; i < files.files.length; i++) {
fileList.push(files.files[i]);
}

 

fileListDisplay.html = '';
fileList.forEach(function (file, index) {
var fileDisplayEl = document.createElement("p");
fileDisplayEl.innerHTML = (index + 1) + ":" + file.name;
fileListDisplay.appendChild(fileDisplayEl);
})
}

function submitFile() {
var formData = new FormData();
//循环添加到formData中
fileList.forEach(function (file) {
formData.append('files', file, file.name);
})

$.ajax({
url: "/Home/UploadFile",
type: 'POST',
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
async: false,
success: function (data) {
if (data) {
}
}
});
}

后台(C#)

/// <summary>
        /// 文件上传到本地
        /// </summary>
        public void Upload()
        {
            try
            {
                HttpFileCollection hpFiles = HttpContext.Current.Request.Files;
                for (int i = 0; i < hpFiles.Count; i++)
                {

                    if (hpFiles[i] == null || hpFiles[i].FileName.Trim() == "")
                    {
                        _Error = 1;
                        return;
                    }
                    string Ext = GetExt(hpFiles[i].FileName);
                    //if (!IsUpload(Ext))
                    //{
                    //    _Error = 2;
                    //    return;
                    //}
                    int iLen = hpFiles[i].ContentLength;
                    if (iLen > _MaxSize)
                    {
                        _Error = 3;
                        return;
                    }

                    if (!Directory.Exists(_SavePath)) Directory.CreateDirectory(_SavePath);
                    byte[] bData = new byte[iLen];
                    hpFiles[i].InputStream.Read(bData, 0, iLen);
                    string FName;
                    if (_IsChangeName)
                    {
                        FName = NewFileName(Ext);
                    }
                    else
                    {
                        FName = hpFiles[i].FileName;
                    }
                    FileStream newFile = new FileStream(_SavePath + FName, FileMode.OpenOrCreate);
                    newFile.Write(bData, 0, bData.Length);
                    newFile.Flush();
                    int _FileSizeTemp = hpFiles[i].ContentLength;

                    string ImageFilePath = _SavePath + FName;

                    newFile.Close();
                    newFile.Dispose();
                    _FileName = hpFiles[i].FileName;
                    _OutFileName = FName;
                    _FileSize = _FileSizeTemp;
                }
                _Error = 0;
                return;
            }
            catch (Exception ex)
            {
                _Error = 4;
                return;
            }
        }

源码下载:https://files.cnblogs.com/files/pukua/UploadDemo.zip