以前ajax不能上传图片 现在有了formdata可以直接ajax上传
代码:
js:
//上传数据
var formData = new FormData($("#form")[0]);
$.ajax({
url: 'DinoVoteHelper.ashx?action=upload',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
debugger
alert(returndata);
},
error: function (returndata) {
alert(returndata);
}
});
后台:
if (context.Request.Files.Count > 0)
{
string filename = context.Request.Files[0].FileName;//获取文件名
string[] temp = filename.Split('.');//获取文件后缀
string path = "photo/DinoVote/" + my_model.id + "_" + DateTime.Now.ToString("MMddHHmmss") +"."+ temp[1];
string strPath = Path.Combine(basePath, path);
context.Request.Files[0].SaveAs(strPath);
hd_articlevote_images img = new hd_articlevote_images()
{
hd_code = DinoVoteManage.hd_code,
images = path,
article_code = my_model.id.ToString()
};
main_db.hd_articlevote_images.Add(img);
main_db.SaveChanges();
}
图片转byte[]:
string str = @"D:\1.png";
//读文件
FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
BinaryReader by = new BinaryReader(fs);
int length = (int)fs.Length;
//转成byte[]
byte[] imgbyte = by.ReadBytes(length);
把byte[]保存为图片类型(如果byte[]不正确则可能保存报错)
//转成IO流
MemoryStream ms = new MemoryStream(imgbyte);
ms.Seek(0, SeekOrigin.Begin);
//通过流生成图片
Image image1 = Image.FromStream(ms);
//保存
image1.Save(@"D:\test.png");
图片上传到服务器(App POST传到后台):
string fPath = context.Server.MapPath("severphotes"); //服务器路径
#region 上传头像
if (!Directory.Exists(fPath)) //判断是否存在文件夹
{
Directory.CreateDirectory(fPath);
}
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); //时间戳
string name = Convert.ToInt64(ts.TotalSeconds).ToString() + ".png"; //图片名
//if (!File.Exists(fPath + name))
//{
System.IO.Stream stream = context.Request.InputStream; //得到传来的流
byte[] buffer = new byte[stream.Length];
FileStream fs = null;
try
{
fs = new FileStream(fPath + "//" + name, FileMode.Create); //按照路径创建图片文件
while ((stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, buffer.Length); //写入数据
}
}
catch (IOException ioe)
{
context.Response.Write(ioe);
}
finally
{
if (fs != null)
{
fs.Close();
}
stream.Close();
}
Form表单提交(input控件添加图片)保存到服务器
1、
System.Web.HttpFileCollection files = context.Request.Files; //获取FORM表单提交的文件
if (files.Count > 0)
{
System.Web.HttpPostedFile postedfile = files[0];
Stream str = postedfile.InputStream;
StreamReader streamReader = new StreamReader(str);
byte[] bytes = new byte[1024];
//地址名字
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string name = Convert.ToInt64(ts.TotalSeconds).ToString() + ".png";
string fPath = "";
string url = "";
string tag = "";
string imgName = "";
if (files.AllKeys[0] == "icon")
{
fPath = context.Request.MapPath("../../../severphotes");
url = ConfigurationManager.AppSettings["website"].ToString() + "severphotes/" + name;
tag = "severphotes/" + name;
imgName = "SF_ICON";
}
#region 保存图片方法
FileStream fstr = new FileStream(fPath + "//" + name, FileMode.OpenOrCreate, FileAccess.Write);
int len = 0;
while ((len = str.Read(bytes, 0, 1024)) > 0)
{
fstr.Write(bytes, 0, len);
}
streamReader.Dispose();
str.Dispose();
fstr.Flush();
fstr.Close();
#endregion
context.Response.ContentType = "text/html"; //这种方式返回能调用JS
}
2、自带Save:
System.Web.HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string name = Convert.ToInt64(ts.TotalSeconds).ToString() + ".png";
string tag = "image/forward/" + name;
string url = ConfigurationManager.AppSettings["website"].ToString() + tag;
HttpPostedFile hpFile = files[0];
hpFile.SaveAs(context.Request.MapPath("../../../image/forward/" + name));
context.Response.ContentType = "text/html";
context.Response.Write(""); //在iframe中调用主页面的script需要加parent.
}
HTML部分:
function setPic(url, tag) { //给图片赋值路径和tag属性,src是为了显示,tag是在数据库保存的相对路径
$('#forwardImg').attr("src", url);
$('#forwardImg').attr("tag", tag);
}
function upload() { //图片上传后提交form
$('#form').submit();
}
function uploadImg() { //控件模拟点击,也可以$("#img").click();
document.getElementById('img').click();
}
样式什么的可以不看,主要的是form、input、iframe、a标签
这里需要给form添加 enctype="multipart/form-data" 否则无法上传
这里第一次点击触发的是uploadImg方法,input就会显示选择文件,确认选择后则自动触发onchange事件提交。在后台可以限制文件大小。