如何在ASP.NET MVC2上上传文件?

时间:2010-09-13 12:26:13

标签: asp.net-mvc-2 file-upload

我正在开发一个多语言漫画网站,所有插入的漫画必须是英语和葡萄牙语。

我在管理多个游戏方面取得了成功:

ComicViewModel.cs:

public class ComicViewModel
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage="A data não pode ficar em branco.")]
    [DisplayName("Data")]
    public DateTime Date { get; set; }

    public IList<LocalizedTextViewModel> Titles { get; set; }
}

LocalizedTextViewModel.cs:

public class LocalizedTextViewModel
{
    public CultureViewModel Culture { get; set; }

    [Required(ErrorMessage = "Este campo não pode ficar em branco.")]
    public string Text { get; set; }
}

CultureViewModel.cs:

public class CultureViewModel
{
    public int Id { get; set; }
    public string Abbreviation { get; set; }
    public string Name { get; set; }

    public CultureViewModel() { }

    public CultureViewModel(Database.Culture culture)
    {
        Id = culture.Id;
        Abbreviation = culture.Abbreviation;
        Name = culture.Name;
    }
}

问题是我无法弄清楚如何管理漫画图片上传。我需要上传多个图像,每个图像都以它的语言为参考。

任何人都有任何想法?

1 个答案:

答案 0 :(得分:1)

以下是上传多个文件的示例:

Html:

<% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%><br />
    <input type="file" name="files" id="file1" size="25" />

    <input type="file" name="files" id="file2" size="25" /> 

    <input type="submit" value="Upload file" />      
<% } %>   

控制器:

[HttpPost]
public ActionResult Upload()
{
    foreach (string inputTagName in Request.Files)
    {
        HttpPostedFileBase file = Request.Files[inputTagName];
        if (file.ContentLength > 0)
        {
            string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
                    , Path.GetFileName(file.FileName));
            file.SaveAs(filePath);
        }
    }

    return RedirectToAction("Index");
}

更新:获取有关上传文件的一些信息

以下示例显示了如何获取已提交的HttpPostedFileBase文件的名称/类型/大小/扩展名。

string filename = Path.GetFileName(file.FileName);

string type = file.ContentType;

string extension = Path.GetExtension(file.FileName).ToLower();

float sizeInKB = ((float)file.ContentLength) / 1024;

假设您上传了文件somePicture.jpeg,输出将是。

filename  > somePicture.jpeg
type      > image/jpeg
extension > jpeg
sizeInKB  > // the file size.