【问题标题】:How to upload an image using fileupload control and save it in a different location如何使用文件上传控件上传图像并将其保存在不同的位置
【发布时间】:2013-06-23 03:57:16
【问题描述】:

我开发了一个 mvc4 razor Web 应用程序来上传一个人的图像并将其保存在自定义位置(文件夹)中。

它有一个文件上传控件、一个文本框和一个按钮。当我使用文件上传控件上传图像时,我需要将其保存在自定义位置,如“D:/Employee/ContactImage”,文件名应该是在文本框中输入的值。

这里是代码

<div id="partial">
            @{Html.RenderPartial("WholeSaleUserDetail");}
            @using (Html.BeginForm("FileUpload", "WholeSaleTrade", new RouteValueDictionary(new { @class = "mainForm" }), FormMethod.Post, new { enctype = "multipart/form-data" }))
            {  
                <input name="uploadFile" type="file" id="fileUpload"/>
                <input type="submit" value="Save Image" id="saveImage" />
                <input type="text" id="imageName">

            }
            <div style="width: 200px; height: 200px;">
                <img id="empimage" src="../../Images/no_image.jpg" alt="" /></div>
        </div>

这是控制器类的代码

[HttpPost]
    public ActionResult FileUpload(HttpPostedFileBase uploadFile, string imageName) 
    {
        var j = new ImageJob(uploadFile, "~/Img/resize/" + imageName, new ResizeSettings(300, 300, FitMode.Stretch, "Jpeg"));
        j.Build();
        string imageUrl = PathUtils.GuessVirtualPath(j.FinalPath);

        return Json(imageUrl, JsonRequestBehavior.AllowGet);
    }

我在这里需要做的就是将文本框的值作为文件名传递,并将图像保存在给定的位置。 请在这里帮助我..

【问题讨论】:

  • 您遇到了什么问题?
  • 主要问题是我无法将文本框值作为文件名传递给控制器​​。在控制器类文件名应该分配给参数名称“imageName”
  • 您是否尝试将 name="imageName" 添加到输入中?如何检查 FormCollection 以查看它是否被回发?

标签: c# asp.net-mvc-4 file-upload razor image-upload


【解决方案1】:

我发现你的代码有问题,输入字段的名称需要与控制器参数匹配。在您的情况下,html 输入没有名称,试试这个。

<div id="partial">
        @{Html.RenderPartial("WholeSaleUserDetail");}
        @using (Html.BeginForm("FileUpload", "WholeSaleTrade", new RouteValueDictionary(new { @class = "mainForm" }), FormMethod.Post, new { enctype = "multipart/form-data" }))
        {  
            <input name="uploadFile" type="file" id="fileUpload"/>
            <input type="submit" value="Save Image" id="saveImage" />
            <input type="text" id="imageName" name="uploadFile">

        }
        <div style="width: 200px; height: 200px;">
            <img id="empimage" src="../../Images/no_image.jpg" alt="" /></div>
    </div>

对于控制器,您可以通过发布的文件获取文件名(它有一个属性)

[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile) 
{
    var j = new ImageJob(uploadFile, "~/Img/resize/" + uploadFile.FileName, new ResizeSettings(300, 300, FitMode.Stretch, "Jpeg"));
    j.Build();
    string imageUrl = PathUtils.GuessVirtualPath(j.FinalPath);

    return Json(imageUrl, JsonRequestBehavior.AllowGet);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-08
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多