Загрузить изображение в vuejs (axios) и веб-API - PullRequest
0 голосов
/ 27 июня 2018

Я успешно загрузил изображение на сервер с помощью axios. Я могу просмотреть изображение в Почтальоне, но я не знаю, как приступить к визуализации изображения в vuejs.

Метод получения:

public HttpResponseMessage Step(int id)
{
    StepService _StepService = new StepService(id);
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    string filepath = HostingEnvironment.MapPath("~/App_Data/Uploads/" + _StepService.GetStepWithProject.step.filename);
    FileStream fileStream = new FileStream(filepath, FileMode.Open);
    Image image = Image.FromStream(fileStream);
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);
    result.Content = new ByteArrayContent(memoryStream.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
    return result;
}

Vuejs

getMoreInfo (step) {
    axios({
        method: 'get',
        url: 'http://localhost:20449/api/steps',
        headers: {
          'Content-type': 'image/jpeg'
        },
        params: {
          id: step.id
        }
     }).then(response => {
        this.more = response.data // I do not think its the right way             
     })
  },

Как отобразить изображение в теге html?

1 Ответ

0 голосов
/ 27 июня 2018

Я нашел решение, которое работает для меня. Я преобразовал изображение в base64.

Метод HttpGet

public string Step(int id)
{
    StepService _StepService = new StepService(id);
    string filepath = HostingEnvironment.MapPath("~/App_Data/Uploads/" + 
    _StepService.GetStepWithProject.step.filename);
     byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
     string base64ImageRepresentation = Convert.ToBase64String(imageArray);
     return base64ImageRepresentation;
}

Шаблон Vue

<img :src="image" alt="Base64 encoded image" />

Функция Axios

getMoreInfo (step) {
    this.image = ''
    axios({
        method: 'get',
        url: 'http://localhost:20449/api/steps',
        headers: {
          'Content-type': 'image/jpeg'
        },
        params: {
          id: step.id
        }
     }).then(response => {
        this.image = 'data:image/jpg;base64,'.concat(this.image.concat(response.data))            
     })
  },

export default {
    data () {
        image: ''
    }
}
...