【问题标题】:Load image in vuejs (axios) and web api在 vuejs (axios) 和 web api 中加载图像
【发布时间】:2018-12-06 06:31:19
【问题描述】:

我已经用 axios 成功上传了一张图片到服务器。我可以在 Postman 中预览图像,但我不知道如何继续在 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标签中渲染图片?

【问题讨论】:

    标签: javascript c# asp.net-web-api vue.js axios


    【解决方案1】:

    我找到了适合我的解决方案。我将图像转换为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: ''
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 2020-12-31
      • 2021-04-11
      • 1970-01-01
      • 2016-05-02
      • 2018-06-03
      • 2019-05-09
      • 1970-01-01
      相关资源
      最近更新 更多