private final static String FILE_UPLOAD_PATH = "D:\\upload\\"; @RequestMapping(value = "/uploadFile",method = RequestMethod.POST) @ResponseBody public R uploadFile(@RequestParam("file") MultipartFile file){ if (file.isEmpty()){ } String fileName = file.getOriginalFilename(); String suffixName = fileName.substring(fileName.lastIndexOf(".")); //生成文件名称通用方法 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); Random r = new Random(); StringBuilder tempName = new StringBuilder(); tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName); String newFileName = tempName.toString(); try { //保存文件 byte[] bytes = file.getBytes(); Path path = Paths.get(FILE_UPLOAD_PATH+newFileName); Files.write(path,bytes); }catch (IOException e){ e.printStackTrace(); } return R.ok().data("url","file:///D:/upload/20231203_15332731.png"); }
前台代码
<el-form-item label="讲师头像"> <!-- 头衔缩略图 --> <pan-thumb :image="teacher.avatar"/> <!-- 文件上传按钮 --> <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像 </el-button> <!-- v-show:是否显示上传组件 :key:类似于id,如果一个页面多个图片上传控件,可以做区分 :url:后台上传的url地址 @close:关闭上传组件 @crop-upload-success:上传成功后的回调 <input type="file" name="file"/> --> <image-cropper v-show="imagecropperShow" :width="auto" :height="auto" :key="imagecropperKey" :url="'http://localhost:8001' + '/upload/uploadFile'" field="file" @close="close" @crop-upload-success="cropSuccess"/> </el-form-item>
标签:文件,springboot,fileName,file,new,tempName,上传,append,String From: https://www.cnblogs.com/sgj191024/p/17873309.html