vue使用el-upload实现文件上传功能

因为我是vue+springboot前后分离,要跨域,就不能用默认的action写请求地址,我用axios时最困扰的就是怎么拿到那个真实的文件,然后给传给后台。

其实可以通过自带的onchanne触发方法获得文件列表,文件信息中那个raw就是真实的文件。

写的时候,刚开始我是直接把el-upload里面的button中加了点击事件,但是每次文件还没选,就已经向后台发出请求了,当然传不过去,于是外面套了个form。

element-ui组件使用可以查看文档

upload.vue

<template>
    <el-form>
       
        <el-form-item label="姓名" prop="name">
            <el-input v-model="name"></el-input>
        </el-form-item>
       
        <el-form-item>
            <el-upload ref="upfile"
                style="display: inline"
                :auto-upload="false"
                :on-change="handleChange"
                :file-list="fileList"
                action="#">
                <el-button  type="success">选择文件</el-button>
            </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button  type="success" @click="upload">点击上传</el-button>
        </el-form-item>
    </el-form>
    
</template>
<script>
export default {
    name:'UploadUi',
    data(){
        return{
            name:'',
            fileList:[]
        }
    },
    methods:{
        //通过onchanne触发方法获得文件列表
         handleChange(file, fileList) {
            this.fileList = fileList;
            console.log(fileList)
        },
        upload(){
            
            let fd = new FormData();
            fd.append("name",this.name);
            this.fileList.forEach(item=>{
                //文件信息中raw才是真的文件
                fd.append("files",item.raw);
                //console.log(item.raw)
            })
            this.$axios.post('/uploadUi',fd).then(res=>{
                if (res.data.code === 200) {
                    //console.log(res);
                    this.$message('上传成功')
                }else{
                    this.$message('失败')
                }
            })
        },
    }
}
</script>

springboot后台 uploadController.java

package com.example.demo.controller;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
 
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import com.example.demo.entity.ListParam;
import com.example.demo.entity.MyUser;
import com.example.demo.entity.Result;
 
@RestController
@ResponseBody
@CrossOrigin
@RequestMapping("/api")
public class UploadController {
    
    @PostMapping("/uploadUi")
    public Result upFile(@RequestParam("name")String name,@RequestParam("files") MultipartFile[] files ) {
         System.out.println("开始");
         System.out.println(name);
         if(files != null) {
             for(MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                System.out.println(fileName);
                try{
                    File mkdir = new File("F:\\app\\file");
                    if(!mkdir.exists()) {
                        mkdir.mkdirs();
                    }
                    //定义输出流,将文件写入硬盘
                     FileOutputStream os = new FileOutputStream(mkdir.getPath()+"\\"+fileName);
                      InputStream in = file.getInputStream();
                      int b = 0;
                      while((b=in.read())!=-1){ //读取文件 
                        os.write(b);
                      }
                      os.flush(); //关闭流 
                      in.close();
                      os.close();
                      
                }catch(Exception  e) {
                    e.printStackTrace();
                    return new Result(401,"失败");
                }
            }
             return new Result(200,"成功");
         }else {
             return new Result(401,"文件找不到");
         }
        
    }
    
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • vue中实现图片和文件上传的示例代码

    html页面 <input type="file" value="" id="file" @change='onUpload'>//注意不能带括号 js代码 methods: { //上传图片 onUpload(e){ var formData = new FormData(); f ormData.append('file', e.target.files[0]); formData.append('type', 'test');

  • vue实现文件上传读取及下载功能

    本文实例为大家分享了vue实现文件上传读取及下载的具体代码,供大家参考,具体内容如下 文件的上传利用input标签的type="file"属性,读取用FileReader对象,下载通过创建a标签实现 <template> <div class="filediv"> <el-button @click="downloadFile">下载</el-button> <div id="fil

  • vue-cli+axios实现文件上传下载功能(下载接收后台返回文件流)

    vue-cli+axios实现附件上传下载记录: 上传: 这里用formData格式传递参数:请求成功后后台返回上传文件的对应信息. 重点是下载: ############## downloadfile(res) { var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'}); //applicati

  • vue webuploader 文件上传组件开发

    最近项目中需要用到百度的webuploader大文件的分片上传,对接后端的fastdfs,于是着手写了这个文件上传的小插件,步骤很简单,但是其中猜到的坑也不少,详细如下: 一.封装组件 引入百度提供的webuploader.js.Uploader.swf css样式就直接写在组件里面了 <template> <div> <div id="list" class="uploader-list"></div> <di

  • SpringBoot+Vue.js实现前后端分离的文件上传功能

    这篇文章需要一定Vue和SpringBoot的知识,分为两个项目,一个是前端Vue项目,一个是后端SpringBoot项目. 后端项目搭建 我使用的是SpringBoot1.5.10+JDK8+IDEA 使用IDEA新建一个SpringBoot项目,一直点next即可 项目创建成功后,maven的pom配置如下 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> &l

  • vue+vux实现移动端文件上传样式

    样式使用的是vux的cell组件 如下图的官方demo样子 上图的样式需要修改一下,把 保护中 修改成一个图片 并且内嵌一个input type='file'  就可以拥有好看的样式的文件上传了 <!--引入组件--> import { Cell } from 'vux' <!--官网的组件是这么写的--> <group> <cell title="title" value="value"></cell>

  • vue中使用input[type="file"]实现文件上传功能

    注意:input[type="file"] 标签中的属性accept="application/msword,application/pdf" 在pc上正常,但是在手机ios和android上这个文件格式限制会被忽略,所以需要在js中增加格式的判断,以及对应显示样式的设置.(我也是刚发现,如果有遇到这个问题的可以参考下---下面有更改:) ``` <template> <div id="my-careers"> <h

  • vue中用H5实现文件上传的方法实例代码

    整理文档,搜刮出一个vue中用H5实现文件上传的方法实例代码,稍微整理精简一下做下分享. 1.图片上传 <img v-if="personInfo.photoUrl" :src="headPreFix + personInfo.photoUrl" style="height:126px;max-width:133px;margin: 25px 0;"> <img v-else src="../../assets/def

  • vue使用axios实现文件上传进度的实时更新详解

    axios 简介 axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征: 从浏览器中创建 XMLHttpRequest 从 node.js 发出 http 请求 支持 Promise API 拦截请求和响应 转换请求和响应数据 取消请求 自动转换JSON数据 客户端支持防止 CSRF/XSRF 引入方式: $ npm install axios //使用淘宝源 $ cnpm install axios //或者使用cdn: <script s

  • vue实现文件上传功能

    vue 文件上传,供大家参考,具体内容如下 首先 先说一下想要实现的效果 就如截图所见,需要将企业和需要上传的文件提交到后台处理,那么接下来就说如何实现 vue 实现 vue 页面代码 <el-upload class="upload-demo" ref="upload" action="doUpload" :limit="1" :file-list="fileList" :before-upload

随机推荐