AJAX文件上传 异步无刷新上传-文件上传

AJAX文件上传 异步无刷新上传-文件上传

一、HTML添加文件标签:

<input type=”file” name=”ImageAddress” /><input type=”button” value=”上传” id=”btnUpload” />

二、添加按钮点击事件:

$(function () {

$("#btnUpload").click(function() {

$("form").ajaxSubmit({

url: "/ActionInfo/Upload",

type:"Post",

success: function(data) {

//返回后台保存图片的服务器地址就可以了。

if (data == "error") {

alert("错误了");

} else {

$("#imgDiv").html("<img src="" + data + "" alt="" />");

$("#IconUrl").val(data);

}

}

});

})

三、添加图片处理程序:

public ActionResult Upload()

{

if (Request.Files.Count > 0)

{

var file = Request.Files[0];

string virthPath = "/Upload/Images/" + Guid.NewGuid().ToString()+file.FileName;

string name = Server.MapPath(virthPath);

file.SaveAs(name);

return Content(virthPath);

}

return Content("error");

}

四、生成图片缩略图

HttpPostedFile file = context.Request.Files["file1"];

string filename = Guid.NewGuid().ToString() + "_" + file.FileName;

int hascode = filename.GetHashCode();

using (Image imageBig = Image.FromStream(file.InputStream))

{

int bWidth = imageBig.Width;

int bHeight = imageBig.Height;

using (Image simage = new Bitmap(200, 200 * bHeight / bWidth))

{

using (Graphics g = Graphics.FromImage(simage))

{

g.DrawImage(imageBig, 0, 0, simage.Width, simage.Height);

}

imageBig.Save(context.Request.MapPath("大图_" + filename));

simage.Save(context.Request.MapPath("小图_" + filename));

}

}

C#编程自学_做最好的.net自学资料站_更多文章请访问:http://www.4k8k.net/

欢迎订阅。

推荐阅读