表格中download显示图片出现 D:\img\undefined (系统找不到指定的文件。)

在加载页面时进行查询图片数据并将其显示与表格中,经常出现图片加载失败的情况就会报出以下错误,但也有时候图片可以显示
对于upload和download的类我应该是写对了,因为按照教程搬下来的

java.io.FileNotFoundException: D:\img\undefined (系统找不到指定的文件。)
    at java.base/java.io.FileInputStream.open0(Native Method)
    at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
    at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158)
    at com.itheima.reggie.controller.CommonController.download(CommonController.java:71)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)

以下是我写的图片upload和download的代码


<template>
        <el-table
                :data="tableData"
                style="width: 100%"
                :row-style="{height: '150px'}"
                :row-class-name="tableRowClassName">

            <el-table-column prop="image" label="图片" align="center">
                <template slot-scope="{ row }">
                    <el-image style="width: auto; height: 40px; border:none;cursor: pointer;"
                              :src="getImage(row.image)"
                              :preview-src-list="[ `/common/download?name=${row.image}` ]" >
                   <!--     <div slot="error" class="image-slot">
                            <img src="./../../images/noImg.png"  style="width: auto; height: 40px; border:none;" >
                        </div>-->
                    </el-image>
                </template>
            </el-table-column>  .........
.....省略下面表格的column....

 <!--新增表单-->
        <el-form ref="form" :model="eventAll" label-width="100px">

            <el-form-item label="图片"  >
                <el-upload
                        ref="upload"
                        action=""
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        :on-remove="handleRemove"
                        :on-change="UploadImage"
                        :limit="1"
                        :file-list="fileList"
                        :auto-upload="false"
                >
                    <i class="el-icon-plus"></i>
                    <template #tip>
                        <div style="font-size: 12px;color: #919191;">
                            单次限制上传一张图片
                        </div>
                    </template>
                </el-upload>
                <el-dialog v-model="dialogVisibleImage" style="line-height: 0;">
                    <img style="width: 100%;height: 100%"  :src="dialogImageUrl" alt="" />
                </el-dialog>
            </el-form-item>
..省略下面的column


下面是关于图片upload和download的methods中的 方法

     /*在表格中显示图片*/
            getImage (image) {
                return `/common/download?name=${image}`
            },


   //上传图片的方法
            UploadImage(file,filelist) {
                //console.log(file);
                let fd = new FormData()
                fd.append('file', file.raw) //传给后台接收的名字 file
                axios.post('/common/upload', fd, {headers: {'Content-Type': 'multipart/form-data'}}).then(response => {
                    //上传成功后返回的数据,
                    console.log("上传图片响应收到");
                    console.log("上传图片到:" + response.data.data);
                    // 将图片地址给到表单.
                    this.eventAll.image=response.data.data
                })

            },

  /*关于上传图片*/
                fileList:[],
                dialogImageUrl: '',
                dialogVisibleImage : false,

                /*控制对话框是否展示*/
                dialogVisible: false,
以下是我写的后台代码
```java
package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件的上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file是一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会删除
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;

        //判断当前目录是否存在
        File dir = new File(basePath);
        if(!dir.exists()){
            //目录不存在,需要创建
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流,通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


getImage(image)方法内,console.log(image)打印一下待下载的文件名称,没问题的话,用字符串拼接的方式拼接在url后面。

java.io.FileNotFoundException: D:\img\undefined (系统找不到指定的文件。)
    

没有找到对应的文件,文件明显不对,首先后缀都不存在。

【以下回答由 GPT 生成】

该问题出现的原因是在表格中显示图片时,图片链接为空,即scope.row.image的值为undefined,导致系统无法找到对应的文件。

解决该问题的方法是在显示图片前,需要检查图片链接是否为空,如果为空则不显示图片。

以下是修改后的代码示例:

<template>
    <el-table
        :data="tableData"
        style="width: 100%"
        :row-style="{height: '150px'}"
        :row-class-name="tableRowClassName">

        <el-table-column prop="image" label="图片" align="center">
            <template slot-scope="scope">
                <img v-if="scope.row.image" :src="scope.row.image" style="width: 100px; height: 100px" />
            </template>
        </el-table-column>

    </el-table>
</template>

在上述代码中,使用了v-if指令来检查图片链接是否为空,如果不为空则显示图片。通过这种方式,即使图片链接为空,也不会再出现文件找不到的错误。

希望以上解决方案能够帮助到您。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^