上传和查看照片

时间:2014-07-30 12:40:49

标签: asp.net-mvc

任何人都可以帮助我使用MVC 5并在上传和显示照片时执行代码并且我有错误(名称'文件'当前不存在内容)请帮忙

这是我使用的控制器:

public class UploadController : Controller
{
    private DataContext db = new DataContext();

    public ActionResult Index()
    {
        var model = new UploadViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Upload(UploadViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }


        UploadDbModel fileUploadModel = new UploadDbModel();
        try
        {
            if (file.ContentLength > 0)
            {

                byte[] uploadFile = new byte[model.File.InputStream.Length];
                model.File.InputStream.Read(uploadFile, 0, uploadFile.Length);

                fileUploadModel.FileName = model.File.FileName;
                fileUploadModel.File = uploadFile;

                db.UploadDbModels.Add(fileUploadModel);
                db.SaveChanges();
            }

            return Content("FILE SUCCESSFULLY UPLOADED");
        }
        catch
        {
            return Content("UPLOAD FAILED");
        }

    }

    public ActionResult Download()
    {
        return View(db.UploadDbModels.ToList());
    }

    public FileContentResult FileDownload(int? id)
    {
        byte[] fileData;
        string fileName;

        UploadDbModel fileRecord = db.UploadDbModels.Find(id);

        fileData = (byte[])fileRecord.File.ToArray();
        fileName = fileRecord.FileName;

        return File(fileData, "text", fileName);
    }


}

2 个答案:

答案 0 :(得分:1)

在Asp.Net MVC中,我们必须使用HttpPostedFileBase来上传文件,如下所示: -

[HttpPost]
public ActionResult Upload(UploadViewModel model, HttpPostedFileBase file)
{
  if (file != null)
    {
        int byteCount = file.ContentLength;   <---Your file Size or Length
        .............
        .............
    }
}

答案 1 :(得分:0)

尝试并使用system.web,只需在程序集上添加引用即可。