赞
踩
前端页面
- <template>
- <el-upload
- class="avatar-uploader"
- action="#"
- :show-file-list="false"
- :before-upload="beforeAvatarUpload"
- :http-request="uploadImg"
- >
- <i class="el-icon-plus avatar-uploader-icon imgbeforepad"></i>
- </el-upload>
- </template>
-
- <script>
- import request from '@/utils/request'
-
- export default {
- props: {
- uploadUrl: String, // 图片上传路径 例: '/ueditor/dynamic/imgUpload;
- },
- data () {
- return {}
- },
- methods: {
- uploadImg (f) {
- const file = f.file
- const form = new FormData()
- form.append('upfile', file)
- this.$http({
- url: request.adornUrl('map/upload/img'),
- method: 'post',
- data: form,
- processData: false,
- contentType: false,
- dataType: 'json',
- async: false,
- })
- .then(({ data }) => {
- debugger
- if (data && data.code === 0) {
- this.$emit('getImgUrl', data.data)
- } else {
- this.$message({
- message: '上传图片失败',
- type: 'warning',
- duration: 1500,
- })
- }
- this.loading = false
- })
- .catch(error => {
- this.loading = false
- console.log(error)
- })
- },
- // 上传图片前的过滤
- beforeAvatarUpload (file) {
- const isLt2M = (file.size / 1024 / 1024) < 1000
- // if (!isJPG) {
- // this.$message.error('上传图片只能是 JPG 格式!')
- // }
- if (!isLt2M) {
- this.$message.error('上传图片大小不能超过 2MB!')
- }
- return isLt2M
- },
- },
- }
- </script>
-
- <style>
- .avatar-uploader .el-upload {
- position: relative;
- overflow: hidden;
- cursor: pointer;
- border: 1px dashed #d9d9d9;
- border-radius: 6PX;
- }
- .avatar-uploader .el-upload:hover {
- border-color: #409EFF;
- }
- .avatar-uploader-icon {
- width: 50PX !important;
- height: 50PX !important;
- font-size: 28PX;
- line-height: 50PX !important;
- color: #8c939d;
- text-align: center;
- }
- .avatar {
- display: block;
- width: 50PX !important;
- height: 50PX !important;
- }
- .imgbeforepad{
- padding-top: 0px !important;
- }
- .avatar-uploader .el-icon-plus{
- margin: 15PX !important;
- }
- </style>
后端接收生成随机名称并存到相应位置,把地址传回前端。
- @PostMapping("/img")
- public Result img(@RequestParam("upfile") MultipartFile file) {
- try {
- if (file.isEmpty()) {
- return Result.failed("上传文件不能为空");
- }
-
- String originalFilename = file.getOriginalFilename();
- String filename = UUID.randomUUID().toString();
- String filetype = originalFilename.split("\\.")[1];
-
- if (filetype.indexOf("jpg") < 0 && filetype.indexOf("png") < 0) {
- return Result.failed("不支持类型");
- }
- String targetFileName = filename + "." + filetype;
- File dest = new File(new File(path).getAbsolutePath() + "/" + targetFileName);
- if (!dest.getParentFile().exists()) {
- dest.getParentFile().mkdirs();
- }
- file.transferTo(dest);
- return Result.ok(UPLOADER + targetFileName);
- } catch (Exception e) {
- e.printStackTrace();
- return Result.failed(e.getMessage());
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。