1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.Mvc;
6 using ImageUploadFilesDome.Models;
7
8 namespace ImageUploadFilesDome.Controllers
9 {
10 [HandleError]
11 public class HomeController : Controller
12 {
13 public ActionResult Index()
14 {
15 int id = 1;//为了演示功能成功所以我这里自定义ID,在正常情况下这个值应该是根据业务传进来的.
16 ImagesRepository imgRepository = new ImagesRepository();
17 Test te = imgRepository.GetFind(id) ?? new Test();
18 return View(te);
19 }
20
21 [HttpPost]
22 public ActionResult Index(HttpPostedFileBase imgUpload, Test model)
23 {
24 ImagesRepository imgRepository = new ImagesRepository();
25 Test te = imgRepository.GetFind(model.ImageId);
26 if (ModelState.IsValid)
27 {
28 //这里我只做文件是否上传,没有对文件处理,如果你想对文件做处理,你就应该实现Image文件规则,必须由model下的ImageRepository类去实现
29 if (imgUpload != null)
30 {
31 byte[] imgBt = new byte[imgUpload.ContentLength];
32 //将接受到文件读到字节数组中
33 imgUpload.InputStream.Read(imgBt, 0, imgUpload.ContentLength);
34 te.ImageFile = imgBt;
35 if (model != null)//判断页面model是否为空,如果为空表示是第一次增加图片,相反就是修改图片
36 {
37 UpdateModel(te);
38
39 }
40 else
41 {
42 imgRepository.AddTest(te);
43
44 }
45 imgRepository.SaveTest(); //保存数据
46 return RedirectToAction("Index");
47 }
48 }
49 return RedirectToAction("Index");
50 }
51
52 public ActionResult ImageFiles(int id)
53 {
54 ImagesRepository imgRepository = new ImagesRepository();
55 Test te = imgRepository.GetFind(id) ?? new Test();
56 if (te.ImageFile != null)
57 {
58 Response.BinaryWrite(te.ImageFile.ToArray());
59 }
60 return View();
61 }
62 public ActionResult About()
63 {
64 return View();
65 }
66 }
67 }
68