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

一.前端

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

<!-- 用户列表 -->
<template>
    <div id="user">
        <!-- 导航开始 -->
        <el-row>
            <el-col :span="24">
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>用户信息</el-breadcrumb-item>
                </el-breadcrumb>
            </el-col>
        </el-row><br>


        <!-- 导航结束 -->


        <!--修改开始-->
        <el-dialog title="用户信息" :visible.sync="dialogFormVisible">


            <el-form :model="user">
          
                <el-form-item label="头像:" :label-width="formLabelWidth"             
                  style="display:inline-block;width:310px">
                    <el-upload class="upload-demo" ref="upload"             
                     :limit="1" action="上传文件要调用的接口路径"
                        :on-change="uploadChange" accept=".jpg" :auto-upload="false">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <div slot="tip" class="el-upload__tip">只支持上传.jpg文件</div>
                    </el-upload>
                </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="btnUpdate()">确 定</el-button>
            </div>
        </el-dialog>
        <!--修改结束-->



        <!-- 数据列表开始 -->
 
        <!-- 数据列表结束 -->



    </div>
</template>



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');
    },
};
</script>

二.springboot后端 

引入maven 依赖

     <!--跨域上传文件-->
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.18.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.18.1</version>
        </dependency>

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

    @PostMapping("/upLoadImg")
    @ResponseBody
    public ResponseResult<Object> 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<Object> 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文件地址是否一致

            

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值