【发布时间】:2012-08-06 09:16:32
【问题描述】:
我有一个控制器方法,它以HttpPostedFileBase picture 作为参数。当然,它用于从表单加载图像。但现在我想使用该方法从另一种方法加载文件。我可以使用图像路径在代码中制作 HttpPostedFileBase 文件吗?或者可能是另一种解决方案是首选?
好的,代码:
public ActionResult UploadPicture(HttpPostedFileBase picture)
{
if (picture.ContentLength > Convert.ToInt32(ConfigurationManager.AppSettings["MaxMBFileSize"]) * 1024 * 1024 || picture.ContentLength == 0)
{
return ClientError(ErrorCodes.ClientErrorCodes.FileSizeError, "File size is incorrect");
}
else
{
string contentType = picture.ContentType;
if (!PictureHelper.ContentTypeIsValid(contentType))
{
return ClientError(ErrorCodes.ClientErrorCodes.MimeTypeError, "Incorrect file type");
}
else
{
string pictureName = Guid.NewGuid().ToString();
pictureName += picture.FileName.Substring(picture.FileName.LastIndexOf('.'));
string serverPath = AppDomain.CurrentDomain.BaseDirectory;
picture.SaveAs(serverPath + ConfigurationManager.AppSettings["LocalImagesPath"] + pictureName);
return Success(new { pictureName = pictureName });
}
}
}
真的,身体绝对不重要。当然我有类似的东西:
<form method="post" action="Photo\UploadPicture">
<input type="file">
<input type="submit" value="submit">
</form>
我想要类似的东西:
public ActionResult NewMethod()
{
string path = ""; // real path to file here
var file = OhMyGodMagicTransfer(path);
// sending request
request.attach(file);
request.send;
}
【问题讨论】:
-
你说你有一个方法,你想重用它。我会说答案可能是“当然,为什么不呢?代码重用是一件好事!”但是您没有发布有关该方法的详细信息,它是如何使用的,以及该方法实际做了什么,所以不可能说。
-
当用户使用表单发布文件时,它会通过 HttpPostedFileBase 参数发布到第一个方法。这很明显。我想在第二种方法中做同样的事情,因为使用了表单。调用第一个方法或给出一些简单的参数非常简单,但我想知道如何给出文件参数。创建 HttpPostedFileBase 对象可能是解决方案,但我不知道它是否真实
-
这对您来说可能很明显,但对于我们这些看不到您的代码的阅读者来说,没有什么是显而易见的。 “文件参数”是什么意思? “这是真的吗?”是什么意思?
标签: c# asp.net-mvc post httppostedfilebase