0

我使用 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;
                } 

in return jquery success method i set this image with src like this :

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

now i could see that the image was saved at server correctly and i can see the src of the image is now "http://localhost:62563/Content/themes/imgs/picture001.jpg"

however i cant browse to the img neither the image is shown in the page after setting the img src. any idea what i could be doing wrong ?

4

1 回答 1

0

这是修复:

我将上传图片更改为:

  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('"',''));
于 2013-09-18T21:41:58.603 回答