栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot项目文件上传的简要步骤

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot项目文件上传的简要步骤

1.controller.java的编写(以自己的项目为例)

 
    @PostMapping("/uploadPhoto")
    public HashMap uploadPhoto(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        HashMap map = new HashMap<>();
        File path=new File(ClassUtils.getDefaultClassLoader().getResource("static").getPath());
        File upload=new File(path.getAbsolutePath(),"upload1");//static/upload1为上传地址
        if (!upload.exists()) {
            upload.mkdir();
        }
        //创建路径
//        String path = request.getServletContext().getRealPath("/upload");
//        File f = new File(path);
//        if (!f.exists()) {
//            f.mkdir();
//        }
//        String path = "D:\code\src\main\resources\static\images\";自己写的死地址
        String oldFilename = file.getOriginalFilename();
        String newFilename = UUID.randomUUID().toString() + oldFilename.substring(oldFilename.lastIndexOf("."));
//        String filepath = path + "/" + newFilename;
        String filepath=upload.getAbsolutePath()+"\"+newFilename;
        file.transferTo(new File(filepath));
        map.put("code", 200);
        map.put("oldFileName", oldFilename);
        map.put("newFileName","/upload1/"+newFilename);
        map.put("fileSize", file.getSize());
        System.out.println("oldFilename: " + oldFilename);
        System.out.println("newFilename: " + newFilename);
        System.out.println("上传的路径: " + path);
        return map;
    }
    @PostMapping("/addUser")
    public HashMap addUser(@RequestBody User u) {
        HashMap map = new HashMap<>();
        u.setCreateTime(new Timestamp(new java.util.Date().getTime()));
        int n = userService.addUser(u);
        if (n > 0) {
            map.put("code", 200);
            map.put("msg", "添加成功");
        } else {
            map.put("code", 401);
            map.put("msg", "添加失败");
        }
        return map;
    }

2.vue组建的编写。

    action里面就是要上传调用的接口。


		
	
			
			
	

        下面是头像上传成功的回调函数和图片限制函数

        

            // 头像上传
			handleAvatarSuccess(res, file) { //res表示服务器返回的json对象,file表示上传的文件
				// this.ruleForm.photo = URL.createObjectURL(file.raw);
				this.ruleForm.photo = res.newFileName, //为添加用户做准备
				console.log("返回的结果:" + res.newFileName);
				this.imgUrls = "http://localhost:9090/images/" + res.newFilename; //服务器返回的新文件名
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/842332.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号