1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public
ActionResult upload()
{
ViewBag.ImageUrl =
" "
;
return
View();
}
// 模型绑定ModelBinding MVC 框架帮你抽取Request值,转换成视图模型对象
[HttpPost]
public
ActionResult upload(List<HttpPostedFileBase> files)
{
if
(files !=
null
)
{
List<
string
> urls =
new
List<
string
>();
foreach
(var file
in
files)
{
if
(file !=
null
&& file.ContentLength > 0)
{
// 1.获取文件名
string
fileName=Path.GetFileName(file.FileName);
string
timeName = DateTime.Now.Ticks.ToString();
// 2.保存文件到网站文件夹
string
localpath=Server.MapPath(
"~/UploadFile/"
);
string
tempName = timeName + fileName;
string
fullpath = localpath + tempName;
file.SaveAs(fullpath);
// 传递到视图图片路径,显示图片
string
temp =
"/UploadFile/"
+ tempName;
urls.Add(temp);
//ViewBag.ImageUrl = fullpath;
// 3.保存的路径存入数据库的地址字段
}
}
ViewBag.urls = urls;
}
return
View();
}
|
后台代码主要使用HttpPostedFileBase对象来操作file这个流对象
前台主要使用form表单工具来提交文件
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@
using
(Html.BeginForm(
"upload"
,
"Order"
, FormMethod.Post,
new
{ enctype =
"multipart/form-data"
}))
{
<input type=
"file"
id=
"files"
name=
"files"
multiple=
"multiple"
/>
<input type=
"submit"
value=
"上传图片"
class
=
"btn btn-default form-control"
/>
}
@
if
(ViewBag.urls !=
null
)
{
foreach
(var url
in
ViewBag.urls)
{
<img style=
"width:300px;"
src=
"@url"
/>
}
}
|