Laravel vue – 上传图片并检索它

huangapple go评论68阅读模式
英文:

Laravel vue - upload image and retrieve it

问题

我有一个名为'case'的表,其中包含一个图像列,我希望用户能够插入case表并能够上传图像,在主页上,用户可以查看每个案例的图像。到目前为止,我已经尝试过以下代码:

用于上传:

<input type="file" id="image" @change="onFileChange" />
methods: {
    onFileChange(e) {
        this.image = e.target.files[0];
    },
    async postcase() {
        const formData = new FormData();
        formData.append('title', this.title);
        formData.append('description', this.description);
        formData.append('amountneeded', this.amountneeded);
        formData.append('caseTypeId', this.selectedcasetype);
        formData.append('uid', this.uid);
        formData.append('visible', 1);
        formData.append('image', this.image);
        try {
            await axios.post('http://127.0.0.1:8000/api/postcase', formData).then(response => {
                console.log(response.data);
            });
        } catch (error) {
            console.log(error);
        }
    }
}

用于检索:

<v-flex class="ma-2" v-for="casee in cases" :key="casee.id" lg3 xs12 md6 sm4>
    <img v-if="casee.image" :src="'/storage/' + casee.image" alt="案例图像">
</v-flex>
mounted() {
    this.getcases();
},
methods: {
    async getcases() {
        try {
            const response = await axios.get('http://127.0.0.1:8000/api/cases');
            this.cases = response.data.cases;
            console.log(this.cases);
        } catch (error) {
            console.log(error);
        }
    }
}

除了图像之外,其他一切都正常。当我尝试检索图像时,它返回错误信息“Cannot GET /storage/public/CQu7g4X98APkiMSbCGlqyiJhaXzLaEk8P0pZXaD3.jpg”。

英文:

i have table 'case' that contains an image column, i want users to insert into the case table and be able to upload an image, on the home page users can view cases along with image of each case.
so far i have tried:

 public function createcase(Request $request){

        $validator = Validator::make($request-&gt;all(), [
            &#39;title&#39; =&gt; &#39;required&#39;,
            &#39;image&#39; =&gt; &#39;required|image|mimes:jpeg,png,jpg,gif,svg|max:2048&#39;,
            &#39;description&#39; =&gt; &#39;required&#39;,
            &#39;caseTypeId&#39; =&gt; &#39;required&#39;,
            &#39;amountneeded&#39; =&gt;&#39;required&#39;,
            &#39;uid&#39; =&gt; &#39;required&#39;,
            &#39;visible&#39; =&gt; &#39;required&#39;,
        ]);
        if ($validator-&gt;fails()) {
            return response()-&gt;json([&#39;error&#39;=&gt;$validator-&gt;errors()], 401);
        }
      $image = $request-&gt;file(&#39;image&#39;);
      $path = $image-&gt;store(&#39;public&#39;);

        $case = casee::create([
            &#39;title&#39; =&gt; $request-&gt;title,
            &#39;description&#39; =&gt; $request-&gt;description,
            &#39;caseTypeId&#39; =&gt; $request-&gt;caseTypeId,
            &#39;amountneeded&#39; =&gt; $request-&gt;amountneeded,
            &#39;uid&#39; =&gt; $request-&gt;uid,
            &#39;visible&#39; =&gt; $request-&gt;visible,
            &#39;image&#39; =&gt; $path,
        ]);
        return response()-&gt;json([&#39;image&#39; =&gt; $image]);

to upload:

  &lt;input type=&quot;file&quot; id=&quot;image&quot; @change=&quot;onFileChange&quot; /&gt;

 methods: {
        onFileChange(e) {
      this.image = e.target.files[0];
    },
  async postcase() {
            const formData = new FormData();
            formData.append(&#39;title&#39;, this.title);
            formData.append(&#39;description&#39;, this.description);
            formData.append(&#39;amountneeded&#39;, this.amountneeded);
            formData.append(&#39;caseTypeId&#39;, this.selectedcasetype);
            formData.append(&#39;uid&#39;, this.uid);
            formData.append(&#39;visible&#39;, 1);
            formData.append(&#39;image&#39;, this.image);
           
            try {
                 await axios.post(&#39;http://127.0.0.1:8000/api/postcase&#39;, formData).then(response =&gt; {
          console.log(response.data);
        })
            
            } catch (error) {
                console.log(response.data);
            }

        }

to retrieve:

  &lt;v-flex class=&quot;ma-2&quot; v-for=&quot;casee in cases&quot; :key=&quot;casee.id&quot; lg3 xs12 md6 sm4&gt; 

                &lt;img v-if=&quot;casee.image&quot; :src=&quot;&#39;/storage/&#39; + casee.image&quot; alt=&quot;Case Image&quot;&gt;

 mounted(){
        this.getcases();
    },
    methods:{
       async getcases(){
            try {
                const response = await axios.get(&#39;http://127.0.0.1:8000/api/cases&#39;);
                this.cases = response.data.cases;
                console.log(this.cases);
            } catch (error) {
                console.log(error);
            }
        },

everything works fine except for the image. it returns the error Cannot GET /storage/public/CQu7g4X98APkiMSbCGlqyiJhaXzLaEk8P0pZXaD3.jpg when i try to retrieve it

答案1

得分: 0

确保存储目录正确地链接到公共目录。
你可以运行以下命令来自动完成:

php artisan storage:link
英文:

Make sure that the storage directory is correctly linked to the public.
You can run this command to make it automatically:

php artisan storage:link

答案2

得分: 0

前端无法访问文件系统中的"/storage/public/FILENAME.jpg"。

如果您使用的是Laravel 9.x,并且没有更改任何文件系统的默认设置,您的文件将被存储在"<项目根目录>/storage/app/public/"下,这是文件系统的默认路径,但前端只能访问"<项目根目录>/public/"文件夹。请按照以下清单检查,可能会帮助您解决问题。

1. 确保您执行了 php artisan storage:link 命令,它会创建一个符号链接,将您的存储路径链接到公共路径。

如果您没有更改设置,它将从"<项目根目录>/storage/app/public"创建链接到"<项目根目录>/public/storage",一旦执行了该命令,您可以在公共文件夹下看到您的存储文件夹。

您可以访问 "<APP_URL>/storage/FILENAME.jpg" 来查看链接是否创建成功,如果没有收到404错误,说明您的链接已经创建成功。

2. 使用Laravel助手函数生成存储URL。

使用 asset() 助手函数来创建文件的URL。

在第1步之后,您的文件将位于"<项目根目录>/public/storage"下,并且您的nginx根目录将默认访问public文件夹,因此您不再需要在URL路径中包含public。

asset('storage/FILENAME.jpg');
// 输出将是 "<APP_URL>/storage/FILENAME.jpg"

3. (非必需)检查Laravel是否缓存了您的视图。

对于一些新的Laravel开发者,他们可能没有注意到Laravel会缓存您的视图,结果他们一直认为代码不起作用。

您可以通过 php artisan about 命令轻松检查Laravel是否缓存了视图,如果您使用的是最新版本的Laravel,请使用 php artisan view:clear 命令来清除视图缓存。

英文:

Frontend couldn't access filesystem as "/storage/public/FILENAME.jpg".

If you are based on Laravel 9.x, and didn't change any filesystem default settings, your file will stored under "&lt;project root&gt;/storage/app/public/", it's filesystem default path, but frontend can only access your "&lt;project root&gt;/public/" folder, do check list as below might help you slove issue.

1.Make sure you executed php artisan storage:link command, and it will created a symbolic link from your storage path to public path.

If you didn't change settings, it will create link from "&lt;project root&gt;/storage/app/public" to "&lt;project root&gt;/public/storage", once you done command you can see your storage folder under public folder.

You can access "&lt;APP_URL&gt;/storage/FILENAME.jpg" to see if link create success or not, if you ain't get 404 means your link created as well as it should be.

2. Use laravel helper to generate storage url.

Use the asset() helper create a URL to the files.

Your files will under "&lt;project root&gt;/public/storage" after step 1, and your nginx root will access public as default, so you don't need public as your url path anymore.

asset(&#39;storage/FILENAME.jpg&#39;);
// output will be &quot;&lt;APP_URL&gt;/storage/FILENAME.jpg&quot;

3. (Not required) Check if laravel cached your view.

For some new developer of laravel didn't notice that laravel will cached your view, and they keep thinking that code doesn't work.

You can easily check if laravel cached view by php artisan about command if you are using latest laravel version, and use php artisan view:clear to clear view cache.

答案3

得分: 0

以下是翻译好的部分:

这是我解决这个问题的方法,如果有人遇到这个问题:

根据之前的答案:

1.php artisan storage:link

2.将 &#39;image&#39; =&gt; $path 替换为 &#39;image&#39; =&gt; basename($path)。

3.&lt;img :src=&quot;&#39;http://127.0.0.1:8000/storage/&#39; + casee.image&quot; alt=&quot;案例图片&quot;&gt;

英文:

heres how i solved it if anyone comes across this issue :
based on the previous answers:

1. php artisan storage:link

  1. replace &#39;image&#39; =&gt; $path to &#39;image&#39; =&gt; basename($path).

3.&lt;img :src=&quot;&#39;http://127.0.0.1:8000/storage/&#39; + casee.image&quot; alt=&quot;Case Image&quot;&gt;

huangapple
  • 本文由 发表于 2023年2月6日 05:27:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定