平时我们需要做个简单的demo,来上传图片,那么我们应该怎么做呢?详细demo如下:
以下是前台demo:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>添加</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.3.1.js"></script>
</head>
<body>
<div align="center">
<form id="form1">
<table class="table table-bordered" style="width:50%;">
<tr>
<td colspan="2" align="center"><h1><b>添加图片</b></h1></td>
</tr>
<tr>
<td>上传图片:</td>
<td><input type="file" id="files" /></td>
</tr>
<tr>
<td><input type="button" value="添加" onclick="add()" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<script>
function add()
{
var ss = new FormData();
ss.append("form1", 1);
ss.append("files", $("#files").get(0).files[0]);
$.ajax({
url: "/Home/Add",
type: "post",
data: ss,
processData: false,
contentType: false,
success: function (data)
{
if (data == 1) {
alert("添加成功");
location.href = "/Home/ShowList";
}
else if (data == 0) {
alert("添加失败");
}
else if (data == 2) {
alert("图片的格式不正确");
}
else
{
alert("请选择要上传的图片");
}
}
})
}
</script>
后台demo如下:
/// <summary>
/// 添加保存
/// </summary>
/// <returns></returns>
public int Add()
{
HttpFileCollectionBase files = Request.Files;//访问客户端上载的文件
if (files.Count > 0)
{
HttpPostedFileBase path = files[0];//获取文件
string text = Path.GetExtension(path.FileName);//扩展名
if (text.Contains(".jpg") || text.Contains(".gif") || text.Contains(".png"))
{
path.SaveAs(Server.MapPath("/Images/") + path.FileName);//将图片保存至服务器
ImagesInfo model = new ImagesInfo(); //实例化model层
model.Imageurl = "/Images/" + path.FileName; //将路径添加到model字段里
if (AddImages(model) > 0) //调用方法,(等同于调用了添加语句)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 2;
}
}
else
{
return 3;
}
}