在服务器上的图像文件路径

时间:2016-10-25 13:31:06

标签: javascript c# jquery asp.net-mvc

我的服务器上保存了一个图像,我希望在客户端上显示该图像。

编辑:我从最多80个列表中选择一个图像。然后根据需要调整此图像的大小并将其返回给客户端。

我的服务器在IIS7 @ localhost:1337上运行。

服务器文件位置:

  

C:\的Inetpub \ wwwroot的\ API \网络\ 4076 \ 1 \ IMG \调整大小\ 1.JPG

这是我返回客户端的绝对路径时返回的路径(请参阅下面的代码)。但客户端无法找到此文件。

我的客户端在IIS7 @localhost:15536​​上运行。

在firebug的帮助下,我可以将客户端应用程序中Image对象的源设置为localhost下服务器上文件的位置。

  

本地主机:1337 /网络/一分之四千○七十六/ IMG /调整大小/ 1.JPG

然后正确显示图像。

问题 我做了哪些更改,以便我自动手动更改?如何创建/返回第二个链接并在与第一个链接相对的客户端中使用它?

服务器API调用

/// <summary>
/// Method to retrieve files from the server. Files will be searched in the requested map depending on size.
/// The resized image will be saved on the server and the location will be send to the client.
/// </summary>
/// <returns>A response message with the location of the newly resized file.</returns>
public HttpResponseMessage getFileResized(string name, int collectionId, int maxWidth, int maxHeight, int version = 1)
{
    // create real file path
    string basePath = FileService.GetPath(collectionId, CollectionType.collection, version) + @"\img\"; //HostingEnvironment.MapPath("~/Cyber/" + collectionId + "/img/");
    string filePath = basePath + @"resized\";
    // Standard location of the file when it's uploaded to the server.
    string fileBase = basePath + name;
    // New location for the resized file on the server.
    string fileExact = filePath + name;
    try
    {
        if (!File.Exists(filePath))
        {
            // create new directories for resizes
            Directory.CreateDirectory(filePath);
        }
        if (//File.Exists(fileBase)) && 
            !File.Exists(fileExact))
        {
            Logger.log("File found but resize missing. Creating resized...");
            ImageService.createResizedFile(name, basePath, maxWidth, maxHeight);
        }
        // check if path and file exist
        string file = Directory.GetFiles(filePath, name, SearchOption.TopDirectoryOnly).FirstOrDefault();

        if (file != null)
        {
            // retrieve the file location, write headers and return it
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Accepted);
            response.Headers.Location = new Uri(file);
            return response;
        }
        else
        {
            // file does not exist at the selected location
            Logger.log("Resized image file does not exist on location: {0}.", fileExact);
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
    }
    catch (DirectoryNotFoundException)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
}

客户端检索文件位置,如

HttpResponseMessage responseMessage = client.GetAsync("api/file/getFileResized?name=" + fileName + "&collectionId=" + CollectionId
    + "&maxWidth=" + maxWidth + "&maxHeight=" + maxHeight + "&version=" + Version).Result;

string sourceResponse = "";
if (responseMessage.IsSuccessStatusCode)
{
    sourceResponse = responseMessage.Headers.Location.AbsolutePath;
    return Json(new { OK = 1, message = sourceResponse, refresh = true }, "text/html");
        }

使用javascript和Jquery将源放入图像src

$("#editorModal").on("shown.bs.modal", function () { showImage(); })

function showImage() {
    console.log("ShowImage resizedSource");
    console.log(resizedSource);

    $("#selectedImage").attr("src", resizedSource);
}

resizedSource在此处理程序中设置

function getResizedImage() {
    $.ajax({
        url: "/NextprintPhotobook/GetResizedImageFile",
        type: "POST",
        data: JSON.stringify({ imageSource: imageSource }),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.OK != 1) {
                showError("Er is een fout opgetreden bij het openen van de foto. Data niet OK.", data.message, data.refresh);
            }
            console.log("getResizedImage data.message");
            console.log(data.message);
            resizedSource = data.message;
        },
        error: function (data) {
            showError("Er is een fout opgetreden bij het openen van de foto.");
        }
    });
}

1 个答案:

答案 0 :(得分:0)

只需将图像路径保存在与服务器相关的web.config的<appSettings>块中

即可
 <add key="ImagePath" value="localhost:1337/Cyber/4076/1/img/resized/" />

然后从此密钥获取路径并从数据库获取映像名称。然后最终创建一个这样的URL:

ImageUrl = ConfigurationManager.AppSettings["ImagePath"]+ ImageName;

其中ImageName是从数据库中提取的图像的名称。将ImageUrl返回到客户端

localhost:1337/Cyber/4076/1/img/resized/1.jpg

ImageName=1.jpg

或者您也可以执行以下动态应用程序路径

var context = HttpContext.Current;
string appPath = string.Format("{0}://{1}{2}{3}",
                                    context.Request.Url.Scheme,
                                    context.Request.Url.Host,
                                    context.Request.Url.Port == 80 ? string.Empty : ":" + context.Request.Url.Port,
                                    context.Request.ApplicationPath);

并使用此appPath动态设置localhost的相对路径。