我想让用户从他/她的计算机中选择一个文件,然后上传到Flickr。关键是,当我从我的电脑上传一个自定义图像时,一切都很好,但是当我为输入文件添加一个额外的字段时,程序突然就不能工作了。
Test.cshtml:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<input type="file" name="file" />
<input type="submit" value="Upload!" />
</fieldset>
}
HomeController.cs:
public ActionResult Upload(HttpPostedFileBase file, FormCollection form)
{
if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null)
{
// Flickr relevant code...
var tmpFilePath = Server.MapPath("~/App_Data/Uploads/Pictures");
if (file == null || file.ContentLength == 0)
{
return RedirectToAction("Index"); // It keeps hitting this!
}
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(tmpFilePath, filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
file.SaveAs(path);
string photoId = flickr.UploadPicture(path, "Test picture");
if (String.IsNullOrEmpty(photoId))
{
System.Diagnostics.Debug.WriteLine("Upload failed!");
}
System.IO.File.Delete(path);
}
else
{
// Flickr relevant code...
}
return View("Test");
}
据我所知,因为MVC是一个服务器端的框架,所以首先我需要将图片上传到我的服务器,然后再上传到Flickr。关键是,我想把文件放在我的App_Data/Upload/Pictures
文件夹中,然后上传到Flickr,然后从那里删除它。所以我想让我的服务器保持干净。
更新:--它一直击中return RedirectToAction("Index");
部件,并重定向。
发布于 2014-07-28 07:56:12
您的表单标记中缺少了enctype="multipart/form-data"
。否则,提交表单时不会将文件数据上载到服务器。
将表单调用更改为:
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
https://stackoverflow.com/questions/24998650
复制相似问题