在Action Method中保存图像,然后将Url返回给客户端

时间:2013-09-18 19:17:17

标签: javascript jquery asp.net-mvc

我使用Jquery ajax上传一个图像,在我的MVC ActionMethod中我有以下代码:

  public JsonResult UploadPicture()
            {
                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                        string filePath = Path.Combine(HttpContext.Server.MapPath("../Content/themes/base/imgs/")
                        , Path.GetFileName(file.FileName));
                        file.SaveAs(filePath);
                        return Json(ResolveServerUrl("/Content/themes/imgs/" + file.FileName ,false));
                    }
                    }
                return Json("failed !");
            }

public static string ResolveServerUrl(string serverUrl, bool forceHttps)
                {
                    if (serverUrl.IndexOf("://") > -1)
                        return serverUrl;

                    string newUrl = serverUrl;
                    Uri originalUri = System.Web.HttpContext.Current.Request.Url;
                    newUrl = (forceHttps ? "https" : originalUri.Scheme) +
                        "://" + originalUri.Authority + newUrl;
                    return newUrl;
                } 

返回jquery成功方法我用src这样设置这个图像:

    $('#imagePreview').attr('src', evt.target.responseText);

现在我可以看到图像已正确保存在服务器上,我可以看到图像的src现在是"http://localhost:62563/Content/themes/imgs/picture001.jpg"

然而,在设置img src之后,我无法浏览到img图像中没有显示图像。任何想法我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

这是修复:

我将uploadPicture更改为:

  public JsonResult UploadPicture()
        {
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/themes/imgs")
                    , Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);
                    var path = Url.Content(Path.Combine("/Content/themes/imgs", file.FileName));// this the difference
                    return Json(path);
                }
                }
            return Json("failed !");
        }

并在javascript中:

        $('#imagePreview').attr('src', evt.target.responseText.replace('"','').replace('"',''));