Vue2.x+Element上传图片并回显或展示返回数据

一、问题

  • 需求:需要将图片上传至后端并回显展示,或展示所需数据

二、解决

  • 利用Element组件Upload上传组件进行解决

  • 其中HTML部分代码如下所示:

    <!-- 上传 -->
    <el-upload :show-file-list="false" action="" :http-request="uploadImg">
    	<el-input v-model="img" placeholder="请上传"></el-input>
    	<img src="@/assets/image/task/file.png" alt=""/>
    </el-upload>
    <!-- 回显 -->
    <img :src="img" alt=""/>
    
  • data()中的数据如下:

    data(){
        return{
            img: '' // 存放回显数据
        }
    }
    
  • 上传的方法uploadImg如下:

    // 上传队伍队徽
    async uploadImg(files) {
        let form = new FormData()
        form.append('file', files.file)
        const res = await this.$postFile(`${this.$url}/src/request_url_in_here`, form)
        this.img = res.url
    }
    
  • 其中$postFile为二次封装axios请求,封装好后挂载到Vue实例对象上面,代码如下:

    export async function $_post_file(url, obj = {}) {
      /* request payload */
      return await axios({
        method: "post",
        url: url,
        headers: {
          'session': "",
          "Content-Type": "'multipart/form-data'"
        },
        transformRequest: [
          function (data) {
            return data;
          }
        ],
        data: obj
      }).then(res => {
        return res.data
      })
    }
    
  • 配置好后点击输入框后即可选择图片文件进行上传,上传成功后会接收到一个图片在服务器上的地址,将这个地址作为参数动态绑定到要回显的img元素中的src上即可回显。

如果你想要实现从 MySQL 数据库中获取文件和表单数据,并在前端页面中显示出来,那么你可以按照以下步骤进行操作: 1. 创建 MySQL 数据库表格,并将文件和表单数据存储在其中。 2. 使用 Spring Boot 创建 RESTful API 接口,从 MySQL 数据库中获取文件和表单数据。 3. 在 Vue.js 前端页面中使用 axios 库调用 Spring Boot 的 RESTful API 接口,获取数据,并将数据展示在页面上。 4. 使用 Element UI 框架中的组件来展示表单数据和文件数据。 下面是具体实现步骤: 1. 创建 MySQL 数据库表格 首先,你需要创建一个 MySQL 数据库表格,来存储文件和表单数据。可以参考以下示例表格: ``` CREATE TABLE `file` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `type` varchar(255) NOT NULL, `size` bigint(20) NOT NULL, `content` longblob NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `form_data` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `age` int(11) NOT NULL, `gender` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; ``` 2. 使用 Spring Boot 创建 RESTful API 接口 在 Spring Boot 中,你可以使用 JPA 来访问数据库,获取文件和表单数据。以下是示例代码: ``` @RestController @RequestMapping("/api") public class FileController { @Autowired private FileRepository fileRepository; @Autowired private FormDataRepository formDataRepository; @PostMapping("/file") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) throws IOException { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); FileModel fileModel = new FileModel(fileName, file.getContentType(), file.getSize(), file.getBytes()); fileRepository.save(fileModel); return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK); } @GetMapping("/file") public ResponseEntity<?> getAllFiles() { List<FileModel> files = fileRepository.findAll(); return new ResponseEntity<>(files, HttpStatus.OK); } @GetMapping("/form-data") public ResponseEntity<?> getAllFormData() { List<FormDataModel> formDataList = formDataRepository.findAll(); return new ResponseEntity<>(formDataList, HttpStatus.OK); } @PostMapping("/form-data") public ResponseEntity<?> createFormData(@RequestBody FormDataModel formDataModel) { formDataRepository.save(formDataModel); return new ResponseEntity<>("Form data created successfully", HttpStatus.OK); } } ``` 3. 在 Vue.js 前端页面中使用 axios 库调用 Spring Boot 的 RESTful API 接口 在 Vue.js 中,你可以使用 axios 库来发送 HTTP 请求,获取数据。以下是示例代码: ``` <template> <div> <el-table :data="formDataList" style="width: 100%"> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="age" label="Age"></el-table-column> <el-table-column prop="gender" label="Gender"></el-table-column> </el-table> <el-upload class="upload-demo" action="/api/file" :on-success="handleSuccess" :show-file-list="false" > <el-button slot="trigger" size="small" type="primary">Click to Upload</el-button> <div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div> </el-upload> <el-table :data="fileList" style="width: 100%"> <el-table-column prop="name" label="Name"></el-table-column> <el-table-column prop="type" label="Type"></el-table-column> <el-table-column prop="size" label="Size"></el-table-column> <el-table-column label="Action"> <template slot-scope="scope"> <el-button type="text" @click="handleDownload(scope.row)">Download</el-button> </template> </el-table-column> </el-table> </div> </template> <script> import axios from 'axios' export default { data() { return { formDataList: [], fileList: [] } }, mounted() { this.getFormDataList() this.getFileList() }, methods: { getFormDataList() { axios.get('http://localhost:8080/api/form-data') .then(response => { this.formDataList = response.data }) .catch(error => console.log(error)) }, getFileList() { axios.get('http://localhost:8080/api/file') .then(response => { this.fileList = response.data }) .catch(error => console.log(error)) }, handleSuccess(response) { this.$message.success('File uploaded successfully') }, handleDownload(row) { const blob = new Blob([row.content]) const link = document.createElement('a') link.href = URL.createObjectURL(blob) link.download = row.name link.click() } } } </script> ``` 4. 使用 Element UI 框架中的组件来展示表单数据和文件数据Vue.js 中,你可以使用 Element UI 框架中的组件来展示表单数据和文件数据。以上面的示例代码为例,我们使用了 el-table 和 el-upload 组件来展示表单数据和文件数据。你可以根据你的需求选择合适的组件来展示数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值