java(Vue+SpringBoot)实现头像上传功能

java实现文件上传功能

网上的其他方法繁琐复杂 不易理解,我总结了下面这种方法,适用于任何技术中,比如Vue+SpringBoot等等。。不废话,上代码:

前端代码:

 <form method="post" action="/upload" enctype="multipart/form-data">
                    <input type="file" name="file"><br>
                    <button type="submit" style="position: absolute;width:80px;height:40px;top:185px;left:305px;">提交</button>
                </form>

这个代码可以放在任何地方,比如element ui的提示框,代码如下:

 <el-dialog title="上传头像提示框" :visible.sync="uploadVisible" width="30%">
            <div class="container-fluid">
                <form method="post" action="/upload" enctype="multipart/form-data">
                    <input type="file" name="file"><br>
                    <button type="submit" style="position: absolute;width:80px;height:40px;top:185px;left:305px;">提交</button>
                </form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="uploadVisible = false">取 消</el-button>
              </span>
        </el-dialog>

后端代码(控制层):以SpringBoot为例接收

在这里插入代码片@PostMapping("/upload")  //上传头像
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
    
    
        HttpSession session = request.getSession();
        User user=(User) session.getAttribute("user");
        int begin = file.getOriginalFilename().indexOf(".");
        int last = file.getOriginalFilename().length();
        //获得文件后缀名: a
        String a = file.getOriginalFilename().substring(begin, last);
        String fileName=user.getAccount()+a;  //我存储的文件名是该用户的账号加文件后缀名,比如201521.jpg
        String filePath = "C:/Users/lenovo/IdeaProjects/police/src/main/resources/static/image/";
        //这个是你的存储路径,为了方便,我用的是绝对路径,直接把文件放在项目的资源文件夹里
        File dest = new File(filePath + fileName);
        try {
    
    
            file.transferTo(dest); //存储!
            //数据库存放的地址,存的是项目相对路径,这个看你们自己
            User user1=new User(user.getAccount(),"../static/image/"+fileName,1); 
            userService.updateUserHeadImage(user1);
        } catch (IOException e) {
    
    
        }
        return "userInfo";
    }

完成啦,虽然简陋,但是很实用,抛开一切的繁杂限制、配置,直接奔向实现功能!

猜你喜欢

转载自blog.csdn.net/weixin_43005654/article/details/123306206
今日推荐