C#文件上传与下载
上传文件 <input type="file" id="file" />
<input type="button" id="upload" value="上传文件" />
<script>
//上传
$("#upload").click(function () {
var formData = new FormData();
var file = document.getElementById("file").files[0];
formData.append("fileInfo", file);
$.ajax({
url: "../api/File/UploadFile",
type: "POST",
data: formData,
contentType: false,//必须false才会自动加上正确的Content-Type
processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
success: function (data) {
alert(data);
},
error: function (data) {
alert("上传失败!");
}
});
});
</script>
/// <summary>
/// 上传文件
/// </summary>
[HttpPost]
public string UploadFile()
{
string result = string.Empty;
try
{
string uploadPath = HttpContext.Current.Server.MapPath("~/App_Data/");
HttpRequest request = System.Web.HttpContext.Current.Request;
HttpFileCollection fileCollection = request.Files;
// 判断是否有文件
if (fileCollection.Count > 0)
{
// 获取文件
HttpPostedFile httpPostedFile = fileCollection[0];
string fileExtension = Path.GetExtension(httpPostedFile.FileName);// 文件扩展名
string fileName = Guid.NewGuid().ToString() + fileExtension;// 名称
string filePath = uploadPath + httpPostedFile.FileName;// 上传路径
// 如果目录不存在则要先创建
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// 保存新的文件
while (File.Exists(filePath))
{
fileName = Guid.NewGuid().ToString() + fileExtension;
filePath = uploadPath + fileName;
}
httpPostedFile.SaveAs(filePath);
result = "上传成功";
}
}
catch (Exception)
{
result = "上传失败";
}
return result;
}
<form action="../api/File/DownloadFile" method="get" id="form">
下载文件 <input type="text" id="name" name="fileName" value="222" />
</form>
<input type="button" id="download" value="下载文件" />
<script>
//下载
$("#download").click(function () {
var form = $("#form");
form.submit();
});
</script>
/// <summary>
/// 下载文件
/// </summary>
[HttpGet]
public void DownloadFile()
{
var request = HttpContext.Current.Request;
NameValueCollection nvCollection = request.Params;
string fileName = nvCollection.GetValues("fileName")[0];
string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), fileName);
if (File.Exists(filePath))
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.Buffer = true;
response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName));
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.ContentType = MimeMapping.GetMimeMapping(fileName);
response.WriteFile(filePath);
response.Flush();
response.Close();
}
}
参考文章:http://blog.ncmem.com/wordpress/2023/12/18/c%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8e%e4%b8%8b%e8%bd%bd/
欢迎入群一起讨论