element UI代码如下,其中on-success为上传成功之后的回调,:headers为请求头设置,可以设置request的请求头,
<el-upload class="avatar-uploader" action="/api/shop/file/upload" :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpload" :headers="getToken()" :onError="uploadError"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload>
beforeUpload(file) { //let fd = new Formdata() //fd.append('key', file.raw, 'fileName') // todo }, // 上传成功后的回调 uploadSuccess(response, file, fileList) { if (response.status == 200) { this.imageUrl = 'http://localhost:9762/api/shop/file/image/' + response.data } else { this.$error('上传失败') } }, // 上传错误 uploadError(response, file, fileList) { console.log('上传失败,请重试!') }, getToken() { var data = { 'token': token().token } return data },
Java代码如下
@RestController @Api(value = "uploadController") @RequestMapping("/api/shop/file") public class uploadController { public static final String ROOT = "upload-dir"; private final ResourceLoader resourceLoader; @Autowired public uploadController(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } //显示图片 @RequestMapping(method = RequestMethod.GET, value = "/image/{filename:.+}") @ResponseBody public ResponseEntity<?> getFile(@PathVariable String filename) { try { return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString())); } catch (Exception e) { return ResponseEntity.notFound().build(); } } //上传图片 @RequestMapping(value = "upload",method = RequestMethod.POST) public Msg upload(MultipartFile file) throws IOException { String name=file.getOriginalFilename(); name=name.substring(name.lastIndexOf(".")); name=UUID.randomUUID().toString().replace("-","")+name; File dir = new File(ROOT); if(!dir.exists()){ dir.mkdirs(); } file.transferTo(Paths.get(ROOT, name)); return Msg.success().addData(name); } }
<style> .avatar-uploader .el-upload { border: 1px dashed #d9d9d9; border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; } .avatar-uploader .el-upload:hover { border-color: #409EFF; } .avatar-uploader-icon { font-size: 28px; color: #8c939d; width: 178px; height: 178px; line-height: 178px; text-align: center; } .avatar { width: 178px; height: 178px; display: block; } </style>