У меня есть изображение, сохраненное на моем сервере, которое я хочу отобразить на клиенте.Путь к файлу на сервере
EDIT: Я выбираю изображение из списка до 80. Это изображение затем при необходимости изменяется и возвращается клиенту.
Мой сервер работает на IIS7 @ localhost: 1337.
местоположение файлаСервер:
C: \ Inetpub \ Wwwroot \ API \ Кибер \ 4076 \ 1 \ IMG \ с новым размером \ 1.jpg
Это путь, который возвращается, когда я верните абсолютный путь клиенту (см. код ниже). Однако клиент не может найти этот файл.
Мой клиент работает на IIS7 @localhost: 15536.
С помощью firebug я могу установить источник объекта Image в клиентском приложении в расположение файла на сервере под локальным хостом.
локальный: 1337/Cyber / 4076/1/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");
}
Источник помещенной в ЦСИ изображения с яваскрипт и Jquery
$("#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.");
}
});
}
Возможный дубликат [Как получить относительный путь от абсолютного пути] (http://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path) – Liam
@Liam Спасибо за ваша помощь. Он работает сейчас. –