SpringBoot+vue实现跨域文件上传,并在linux上搭建tomcat文件服务器

一.前端

前端我使用的是vue发送ajax请求实现文件上传,其它前端框架调用方式也是与此类似






export default {
    name: "",
    data() {
        return {
            
            dialogFormVisible: false, //对话框表单是否显示
            formLabelWidth: '100px',   //对话框宽度
            user: {},
            file: null,        //上传的文件
        };
    },
    methods: {
        //当文件上传组件发生改变,将文件赋值给file
        uploadChange(file) {
            this.file = file
        },

        //文件保存
        btnUpdate: function () {
            //创建formData对象
            let formData = new FormData(); 

            if (this.file != null) {
                formData.append("myfile", this.file.raw); //添加要上传的文件相关的信息
            }

            formData.append("username", this.user.username); //请求行中用户id
           
            //请求头
            const params = {
                headers: { "Content-Type": "multipart/form-data;boundary=" + new Date().getTime() }
            };
            
            axios.post("/api/user/upLoadImg", formData, params).then(res => {
                if (res.data.status == 200) {
                   
                    // 隐藏自己
                    this.dialogFormVisible = false;

                   
                    // 调用查询数据
                

                } else {
                    this.$message({
                        showClose: true,
                        message: res.data.msg,
                        type: 'warning'
                    });
                }
            })
                .catch((err) => {
                    this.$message({
                        showClose: true,
                        message: err,
                        type: 'error'
                    });

                })
        }
    },

    created() {
        //获取用户id
        this.user.username = window.localStorage.getItem('username');
    },
};

二.springboot后端 

引入maven 依赖

     
        
            com.sun.jersey
            jersey-core
            1.18.1
        
        
            com.sun.jersey
            jersey-client
            1.18.1
        

通过jersey客户端连接,实现文件跨域上传。springboot后台文件上传接口,形参中文件名需与前端传入的文件名一致,否则会出现异常

    @PostMapping("/upLoadImg")
    @ResponseBody
    public ResponseResult doUpload(@RequestBody MultipartFile myfile,  User user){

           String filename=null;  //文件名
          if(!StringUtils.isEmpty(myfile)){
              //tomcat文件服务器地址
              String path="http://192.172.0.17:8090//uploadfiles/";
              //为上传到服务器的文件取名,使用UUID防止文件名重复
              String type=myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf("."));
              filename= UUID.randomUUID().toString()+type;

              try{
                  //使用Jersey客户端上传文件
                  Client client=Client.create();
                  WebResource webResource=client.resource(path+"/"+ URLEncoder.encode(filename,"utf-8"));
                  webResource.put(myfile.getBytes());


              }catch(Exception ex){
                  System.out.println("上传失败");
              }
          }
       
        user.setAvatarUrl(filename);//修改头像,将文件全地址存入数据库

        ResponseResult responseResult = null;
         if(userService.saveOrUpdate(user)){
            responseResult = new ResponseResult<>("修改用户信息成功", "OK", 200);
        }

        return responseResult;
    }

        代码中ResponseResult工具类请参考文章:

通过redis实现SpringBoot接口幂等性的自定义注解

        tomcat安装方式请参询我另一篇文章笔记:

Linux下配置MySQL数据库和Tomcat 应用服务器

       在tomcat安装目录中的webapps目录里面创建图片上传文件夹uploadfiles,创建命令

find / -name webapps |  mkdir uploadfiles

      注意:1.如果有多个tomcat需要在同一个运行环境启动,需要注意改变tomcat端口

                 2.上传文件时需注意文件上传url是否和tomcat文件地址是否一致

            

你可能感兴趣的:(spring,boot,tomcat,java)