简易的springboot上传头像(图片)代码片段"/>
简易的springboot上传头像(图片)代码片段
/*** 上传头像** @throws IOException* @throws IllegalStateException*/public String upload(MultipartFile file) throws IllegalStateException, IOException {File dir = new File(rootpath);if (!dir.exists()) {dir.mkdirs();}//读取文件名String fileName = file.getOriginalFilename();if (!StringUtil.isEmpty(fileName)) {//获取文件的后缀String suffix = FilenameUtils.getExtension(fileName);//UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法,生成唯一的标识//修改后的文件名(带后缀)String newFileName = UUID.randomUUID().toString().toLowerCase() + "." + suffix;//public File(File parent, String child)--->dir就是相当于这个文件的路径(不包含这个文件的文件名),newFileName指的是文件名;File targetFile = new File(dir, newFileName);//将文件提交到目的地文件系统中file.transferTo(targetFile);System.out.println(newFileName + "mmm");//图片上传以后,“\\”要变成“/”、而且前面的根路径也不需要了;String imgpath = targetFile.getPath().replace("\\", "/").replace(rootpath, "");System.out.println(imgpath);return imgpath;} else {return null;}}
更多推荐
简易的springboot上传头像(图片)代码片段
发布评论