asp.net mvc 上传下载文件的几种方式
2024-08-22 08:03:07
view:
<!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.form.js"></script>
</head>
<body>
<div>
页面上传需要注意以下几点:<br />
1、同一个页面可以有不止一个form但是不能嵌套<br />
2、form:method="post" enctype="multipart/form-data"<br />
3、input:type="file" name="XX" 必须要有name值<br />
</div> <div style="margin-top:20px;">
submit直接提交:提交后刷新页面,直接使用ajax不能把file传到后台处理<br />
<form method="post" action="UpLoadPic" enctype="multipart/form-data">
<input type="file" name="filename" id="filename" accept="image/*" />
<input type="submit" value="提交" />
</form>
</div> <script>
$(function () {
var options = {
success: function (data) {
alert("成功");
}
}; //$("#myform1").ajaxForm(options); $("#myform1").submit(function () {
$(this).ajaxSubmit(options);
return false;
});
});
</script>
<div style="margin-top:20px;">
jQuery.Form.js参照:http://www.cnblogs.com/heyuquan/p/form-plug-async-submit.html <br />
http://www.vaikan.com/docs/jquery.form.plugin/jquery.form.plugin.html <br />
http://www.cnblogs.com/xiaofeixiang/p/3676597.html <br />
每次还会刷新页面
<form id="myform1" method="post" action="UpLoadPic1" enctype="multipart/form-data">
<input type="file" name="filename1" id="filename1" accept="image/*" />
<input id="tijiao1" type="submit" value="提交" />
</form> <div id="outputdiv"></div>
</div> <script src="~/Scripts/ajaxfileupload.js"></script>
<div style="margin-top:20px;">
ajaxfileupload.js参照:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html <br />
<form method="post" action="GetPic" enctype="multipart/form-data">
<input type="file" name="filename2" id="filename2" accept="image/*" />
<input type="button" value="提交" onclick="f2submit();" />
</form>
<script>
function f2submit() {
//文件上传
$.ajaxFileUpload({
url: 'UpLoadPic2',
secureuri: false,
fileElementId: 'filename2',
success: function () {
alert("成功");
},
error: function () {
alert("失败");
},
});
return false;
}
</script>
</div> <script src="~/Scripts/uploadify/jquery.uploadify.min.js"></script>
<div style="margin-top:20px;">
jquery.uploadify.js参照:http://blog.sina.com.cn/s/blog_5079086b0101fkmh.html <br />
局部刷新
<form method="post" enctype="multipart/form-data">
<input type="text" id="FilePathName" readonly="readonly" style="width: 300px;" />
<input type="file" name="filename3" id="filename3" accept="image/*" />
<input type="button" value="提交" onclick="f3submit()" />
</form>
<script>
$(function () {
$('#filename3').uploadify({
//'multi': false,
//'uploadLimit': 100,
auto: false, // 是否直接上传
//width: 64,
//height: 28,
buttonText: "浏览",
'fileSizeLimit': '20MB',
'fileTypeExts': '*.doc;*.docx;*.xlsx;*.pdf;*.ppt;*.pptx;*.xls;*.jpg;*.png;',
swf: '/Scripts/uploadify/uploadify.swf',
//uploader: '/Scripts/uploadify/UploadFile.ashx',
uploader: '/Home/UpLoadPic3',
onSelect: function (file) {
$("#FilePathName").val(file.name);
},
'onSelectError': function (file, errorCode, errorMsg) {
if (errorCode == -110) {
errorMsg = "文件大小不能超过20MB!";
}
else if (errorCode == -100) {
errorMsg = "已经有文件在队列中,请先取消之前的文件!";
}
else if (errorCode == -130) {
errorMsg = "文件格式错误,请选择正确格式的文件!";
}
else {
errorMsg = "未知错误!";
}
alert(errorMsg); return false;
},
onUploadSuccess: function (file) {
alert("成功");
}
});
});
function f3submit() {
$('#filename3').uploadify('upload');
} </script>
</div> <div style="margin-top:20px;">
FormData提交参照:http://www.cnblogs.com/hutuzhu/p/4409292.html <br />
FormData为HTML5对象,只支持新浏览器<br />
<form id="myform4" name="myform4">
<input type="file" name="filename4" id="filename4" accept="image/*" />
<input type="button" value="提交" onclick="f4submit()" />
</form>
<script type="text/javascript">
function f4submit() {
var form = document.getElementById("myform4");
var formData = new FormData(form);
var oReq = new XMLHttpRequest();
oReq.onreadystatechange = function () {
if (oReq.readyState == 4) {
if (oReq.status == 200) {
alert(xhr.responseText);
}
else {
alert("失败");
}
}
}
oReq.open("POST", "UpLoadPic4");
oReq.send(formData);
return false;
}
</script>
</div> <hr />
<a href="/Home/GetFileByContent">根据文件内容下载二进制方式上传的文件</a>
<br />
<a href="/Home/GetFileByPath">根据文件保存路径下载上传的文件</a>
</body>
</html>
controller:
public static string FilePath = string.Empty;
public static byte[] FileContent; /// <summary>
/// 视图
/// </summary>
/// <returns></returns>
public ActionResult UpFile()
{
return View();
} /// <summary>
/// submit
/// </summary>
[HttpPost]
public void UpLoadPic()
{
SaveFileDirect();
//SaveFileStream();
Response.Redirect("Upfile");
} /// <summary>
/// ajaxSubmit
/// </summary>
[HttpPost]
public void UpLoadPic1()
{
SaveFileDirect();
//SaveFileStream();
Response.Redirect("Upfile");
} /// <summary>
/// ajaxfileupload.js
/// </summary>
[HttpPost]
public void UpLoadPic2()
{
//SaveFileDirect();
SaveFileStream();
} /// <summary>
/// jquery.uploadify.js
/// </summary>
public void UpLoadPic3()
{
//SaveFileDirect();
SaveFileStream();
} /// <summary>
/// FormData
/// </summary>
public void UpLoadPic4()
{
//SaveFileDirect();
SaveFileStream();
} /// <summary>
/// 直接保存上传文件到指定目录
/// </summary>
public void SaveFileDirect()
{
// 获取文件
var upfile = Request.Files[];
// 拼接保存路径
string uppath = Server.MapPath("~/UpFile/") + Path.GetFileName(upfile.FileName);
// 存入指定目录
if (upfile.ContentLength > )
{
upfile.SaveAs(uppath);
} FilePath = uppath;
FileContent = null;
} /// <summary>
/// 通过二进制流保存文件,可以存入数据库
/// </summary>
public void SaveFileStream()
{
// 获取文件
var upfile = Request.Files[];
// 拼接保存路径
string uppath = Server.MapPath("~/UpFile/") + Path.GetFileName(upfile.FileName);
// 读入文件流
byte[] temp = new byte[upfile.InputStream.Length];
upfile.InputStream.Read(temp, , (int)upfile.InputStream.Length);
// 写到指定目录
using (FileStream fs = new FileStream(uppath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Write(temp, , temp.Length);
}
FilePath = uppath;
FileContent = temp;
} /// <summary>
/// FileContentResult方式下载
/// </summary>
/// <returns></returns>
public FileResult GetFileByContent()
{
List<string> typeList = new List<string>() { ".png", ".jpg", ".jpeg" };
string FileName = Path.GetFileName(FilePath); if (FileContent != null && FileContent.Length > )
{
if (typeList.Contains(Path.GetExtension(FileName)))
{
return File(FileContent, "image/jpg");
}
// 存在fileDownLoad属性的FileResult以附件形式下载,默认会以内联方式打开
return File(FileContent, "application/octet-stream", FileName);
}
return null;
} /// <summary>
/// FilePathResult方式下载
/// </summary>
/// <returns></returns>
public FileResult GetFileByPath()
{
List<string> typeList = new List<string>() { ".png", ".jpg", ".jpeg" };
string FileName = Path.GetFileName(FilePath); if (FileName != null)
{
if (typeList.Contains(Path.GetExtension(FileName)))
{
return File(FilePath, "image/jpg");
}
// 存在fileDownLoad属性的FileResult以附件形式下载,默认会以内联方式打开
return File(FilePath, "application/octet-stream", FileName);
}
return null;
}
最新文章
- 基于MVC4+EasyUI的Web开发框架经验总结(13)--DataGrid控件实现自动适应宽带高度
- Intel微处理器学习笔记(五) 中断
- Farseer.Net
- viewpage的使用
- c# 轻量级 ORM 框架 之 Model解析 (四)
- PAT 1038 体验Python之美
- UNIX环境高级编程——TCP/IP网络编程
- Python 代码规范
- My first_leetcode_Rever Ingeter 数字翻转java实现(办法集合)
- Kindeditor JS 取值问题以及上传图片后回调等
- shell中的wait
- AutoCAD下载
- 使用 Python 爬取网页数据
- web服务器的原理
- 第4次oo作业
- java 判断元素是否在数组内
- Solr7.1--- 高亮查询
- gcc 的参数 -Wall -O2 -ansi
- Estimating the number of receiving nodes in 802.11 networks via machine learning
- AS 功能 设置 SDK AVD 简介 MD