Gio*_*lbo 5 asp.net-mvc file-upload
我是ASP.net MVC的新手,所以请在答案中尽可能描述:)
让我简化一下我要做的事情.想象一下,我有一个表格,您想要输入有关汽车的一些信息.字段可能是:Make,Model,Year,Image1,Image2.
表单底部是"保存"按钮.关联的Controller方法将Image1和Image2保存到磁盘,获取文件名并将其与汽车模型关联,然后将其保存到数据库中.
有任何想法吗?
多谢你们!
编辑
winob0t让我大部分都在那里.唯一突出的问题如下:Image1和Image2不是必填字段,所以我现在可以保存0,1或2个图像; 但如果用户只上传了1张图片,我无法知道它是来自imageUpload1还是imageUpload2.
再次,任何帮助表示赞赏!
在您的控制器中,您可以访问上传的文件:
if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
HttpPostedFileBase postFile = Request.Files.Get(0);
string filename = GenerateUniqueFileName(postFile.FileName);
postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
}
protected virtual string GenerateUniqueFileName(string filename) {
// get the extension
string ext = Path.GetExtension(filename);
string newFileName = "";
// generate filename, until it's a unique filename
bool unique = false;
do {
Random r = new Random();
newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
unique = !File.Exists(FileDirectoryPath + newFileName);
} while(!unique);
return newFileName;
}
Run Code Online (Sandbox Code Playgroud)
文本字段将按照通常的方式到达您的控制器操作,即Request.Form [...].请注意,您还需要将表单上的enctype设置为"multipart/form-data".听起来你对ASP.NET MVC的理解已经足够了.另请注意,您可以在aspx视图中声明表单标记,如下所示,但如果您愿意,可以使用更传统的方法.
<% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %>
<% } %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4838 次 |
| 最近记录: |