0

I have an image saved on my server which I want to display on the client.

EDIT: I select an image from a list of up to 80. This image is then resized if needed and returned to the client.

My server is running on IIS7 @ localhost:1337 .

Server file location:

C:\inetpub\wwwroot\API\Cyber\4076\1\img\resized\1.jpg

This is the path that's returned when I return the absolute path to the client (see code below). The client however can't find this file.

My Client is running on IIS7 @localhost:15536.

With the help of firebug I can set the source of the Image object in the client application to the location of the file on the server under localhost.

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

It then correctly displays the image.

Question What changes do I make so that the changes I did manually happen automatically? How do I create/return the second link and use it in the client opposed to the first link?

Server API call

/// <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);
    }
}

Client retrieves the file location like this

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");
        }

The source is put into the image src with javascript and Jquery

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

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

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

resizedSource is set in this handler

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.");
        }
    });
}
Da Bazz
  • 61
  • 2
  • 13
  • 1
    Possible duplicate of [How to get relative path from absolute path](http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path) – Liam Oct 25 '16 at 13:42
  • @Liam Thanks for your help. It works now. – Da Bazz Oct 26 '16 at 09:19

1 Answers1

0

Simply save the image path in the <appSettings> block of web.config with respect to your server

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

And then get the path from this key and the image name from database. Then finally create a URL like this:

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

Where ImageName is the name of image extracted from database. Return the ImageUrl to the client which will be

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

when ImageName=1.jpg

Or you can also do the following for dynamic application path

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);

And use this appPath for setting the relative path to the localhost dynamically.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • This is wrong. There is no need to hard code your path into the config, [see here](http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path) – Liam Oct 25 '16 at 13:43
  • If the same path is used multiple times in the server code then this is much cheaper operation that the one you are talking about. – Ankit Agarwal Oct 25 '16 at 13:46
  • What makes you think that? The processing involved in manipulating a string is miniscule. It's actually probably more processing to serialise the appSettings XML into memory (though you'd imagine this is cached). I'd say there would be very little difference in terms of processing in both these methods and yours is considerably more fragile. Any difference I'd suggest would be so tiny as to be virtually unmeasurable, though you could benchmark it to prove your point? – Liam Oct 25 '16 at 13:58
  • @Liam Any idea how I set the relative path to the localhost dynamically? I can't imagine changing the string "C:\inetpub\wwwroot\API" to "localhost:1337" is a good solution. What if the host/port changes I have to go back and changes these manually. – Da Bazz Oct 25 '16 at 14:05
  • @AKA Unfortunatly I'm not always using the same path. The Cyber (in this case 4076) increases when a client adds a new bundle of images. I could see how your solution works but I don't think it's useful in this scenario. – Da Bazz Oct 25 '16 at 14:06
  • I have added the solution which should probably work in your case for dynamic getting of relative path. Look at it. – Ankit Agarwal Oct 28 '16 at 06:34