简体   繁体   English

用vue和playframework访问动态图片

[英]Access to dynamic Images with vue and playframework

I use vue and Play.Framework for my project.我在我的项目中使用 vue 和 Play.Framework。

Fronted: Vue.js 2.6.12 Backend: Play.Framework with Scala (2.12.8)前端:Vue.js 2.6.12 后端:Play.Framework with Scala (2.12.8)

I use following Code snippet to upload an image to my server (This is copied from here: https://www.playframework.com/documentation/2.8.x/ScalaFileUpload我使用以下代码片段将图像上传到我的服务器(这是从这里复制的: https://www.playframework.com/documentation/2.8.x/ScalaFileUpload

  def uploadImage = Action.async{   implicit request =>
         
        request.body.asMultipartFormData.map{ pic =>
            val file = pic.files

           val userIdTemp = pic.asFormUrlEncoded("userId")
           val userId = userIdTemp.head.toInt

           val itemIdTemp = pic.asFormUrlEncoded("itemId")
           val itemId = itemIdTemp.head.toInt

            val contentType = file.head.contentType
            val filename    = Paths.get(file.head.filename).getFileName.toString().toLowerCase()
            val fileSize    = file.head.fileSize
            print("content Type: "+contentType)
            print("filename: "+filename)
            print("filesize: "+fileSize)
            

            file.head.ref.moveFileTo(Paths.get(s"...\\vui\\src\\assets\\"+filename).toFile, replace = true)
           
           
            print("***********************uploadImage -3")
            service.saveImage(userId,itemId, filename.toString()) map{ foundItems =>
                Ok(Json.toJson(foundItems))
            }

        }.getOrElse(null) // change me
    }

I upload the image to the server and save the url related to an item in my database.我将图像上传到服务器,并将与某个项目相关的 url 保存在我的数据库中。 This works fine.这很好用。 I display the images in my fronted with following code snippet:我使用以下代码片段在前面显示图像:

<b-carousel-slide  :img-src="require('../../assets/'+img.imgUrl)" >
</b-carousel-slide>

When i try to upload an image which i have uploaded before it works fine, but if i try to upload an image for the first time i get following exception:当我尝试上传之前上传的图片时,它工作正常,但如果我第一次尝试上传图片,我会遇到以下异常:

Error: Cannot find module './001.jpg'
    webpackContextResolve .*$:70
    webpackContext .*$:65
    render FoodMenuItem.vue:1302
    renderList VueJS
    render FoodMenuItem.vue:1274
    VueJS 14
    createNewImages FoodMenuItem.vue:809
    uploadImage FoodMenuItem.vue:802
    promise callback*p$1.then vue-resource.esm.js:230
    uploadImage FoodMenuItem.vue:799
    onSelect FoodMenuItem.vue:720
    VueJS 33
    updateTarget transporter.js:145
    updated transporter.js:98
    VueJS 13
    click FoodMenuItem.vue:1256
    VueJS 3
vue.runtime.esm.js:1897
    VueJS 17
    createNewImages FoodMenuItem.vue:809
    uploadImage FoodMenuItem.vue:802
    then vue-resource.esm.js:230
    uploadImage FoodMenuItem.vue:799
    onSelect FoodMenuItem.vue:720
    VueJS 33
    updateTarget transporter.js:145
    updated transporter.js:98
    VueJS 13
    click FoodMenuItem.vue:1256
    VueJS 3

The images is uploaded and the url is saved in the database, but my frontend crashed.图片已上传,url 已保存在数据库中,但我的前端崩溃了。 When i "complete" refresh my browser and try it again, evertything works fine.当我“完成”刷新我的浏览器并再次尝试时,一切正常。 My guess is, i can not access to image with require who are not loaded?我的猜测是,我无法使用未加载的 require 访问图像?

Is there a way to display this images without refreshing the browser?有没有办法在不刷新浏览器的情况下显示这些图像? Is that a normal way to handle images in a web application?这是在 web 应用程序中处理图像的正常方式吗? Any help will help!任何帮助都会有所帮助!

If u need more information to help, just ask me:)如果您需要更多信息来提供帮助,请问我 :)

Thank you!谢谢!

I tried a lot of things and i followed this steps:我尝试了很多东西,然后按照以下步骤操作:

https://blog.lichter.io/posts/dynamic-images-vue-nuxt/ https://blog.lichter.io/posts/dynamic-images-vue-nuxt/

As i told you above, i am uploading my images at the moment to the assets folder in UI.正如我在上面告诉你的,我正在将我的图像上传到 UI 中的资产文件夹。 If i am in dev mode i can upload new images and show them with following code:如果我处于开发模式,我可以上传新图像并使用以下代码显示它们:

<img :src="require(`../../assets/${img.imgUrl}`)" >

And this works now.这现在有效。 But when i change in production mode with:但是当我改变生产模式时:

  1. npm run build npm 运行构建
  2. sbt compile stage sbt 编译阶段
  3. sbt start sbt开始

The Frontend App will be a static app in the folder public/ui/前端应用程序将是文件夹 public/ui/ 中的 static 应用程序

and then i don´t know the right relative path for the new images...然后我不知道新图像的正确相对路径......

vue.config.js: vue.config.js:

const path = require("path");

const webpack = require('webpack')

module.exports = {
outputDir: path.resolve(__dirname, "../public/ui"),
assetsDir: process.env.NODE_ENV === 'production' ? 'static':'',

devServer: {
    public: 'localhost:8080',
    headers: {
        'Access-Control-Allow-Origin': '*',
    }
},

configureWebpack: {
    plugins: [
        new webpack.DefinePlugin({
            'process.conf': {
                'RECAPTCHA_SITEKEY': JSON.stringify(process.env.RECAPTCHA_SITEKEY)
            }
        })
    ]
},

chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.transformAssetUrls = {
          img: 'src',
          image: 'xlink:href',
          'b-avatar': 'src',
          'b-img': 'src',
          'b-img-lazy': ['src', 'blank-src'],
          'b-card': 'img-src',
          'b-card-img': 'src',
          'b-card-img-lazy': ['src', 'blank-src'],
          'b-carousel-slide': 'img-src',
          'b-embed': 'src'
        }

        return options
      })
      
  }

} }

In which folder do i have upload the images?我在哪个文件夹中上传图像? How can i reach the new uploaded images in production mode?如何在生产模式下获取新上传的图片?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM