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;
}

最新文章

  1. onDestroy &#160;和 onBackPressed、onfinish 的区别
  2. MVC API 权限控制
  3. Repeater控件使用中的一些小问题
  4. 【2016-10-13】【坚持学习】【Day4】【virtual 虚函数】
  5. 提交上了,却在iTunes Connect没有新版本的任何消息
  6. Codeforces 696D Legen...(AC自动机 + 矩阵快速幂)
  7. oracle中number类型的数据使用as string 得到的值为null
  8. 使用Dapper时,如何将MySqlParameters[] 变成Dapper.DynamicParameters动态对象
  9. JS高级程序设计2nd部分知识要点7
  10. unity3d web.config设置
  11. javascript 拷贝文本
  12. 跟大家分享下今天所学到的PHP,虽然很基础,但是感觉也很重要
  13. Selenium2Library中的Get Alert Message
  14. iOS开发——Swift篇&amp;Swift关键字详细介绍
  15. 【Xamarin挖墙脚系列:现有IPhone/IPad 设备尺寸】
  16. Eclipse ADT 更换主题
  17. 详解 swift2.2 和 OC 的混编
  18. 基于 OS X Mavericks 系统
  19. Scrapyd 改进第一步: Web Interface 添加 charset=UTF-8, 避免查看 log 出现中文乱码
  20. java获取当前时间精确到毫秒

热门文章

  1. iOS蓝牙调用的一般流程
  2. Web Api初试
  3. bootstrap插件学习-bootstrap.dropdown.js
  4. Ajax实现天气预报功能
  5. JavaEE:Servlet简介及ServletConfig、ServletContext
  6. squid和varnish的小结
  7. tag标签记录
  8. [ActiveX]使用VS2010创建MFC ActiveX工程项目
  9. autotools入门笔记(二)——创建和使用静态库、动态库
  10. java基础知识拾遗(四)