在操作方法中保存图像,然后将 URL 返回给客户端

Saving image in ActionMethod then returning Url to client

本文关键字:URL 返回 客户端 然后 操作方法 保存 图像      更新时间:2023-09-26

我使用 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 设置后,图像也不会显示在页面中。 知道我可能做错了什么吗?

这是修复:

我将上传图片更改为:

  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('"',''));