毕设-element ui + springboot 实现图片上传显示

文件上传

流程

前端文件上传时携带cookie,内容为当前登录的用户的token。

后端接收到文件后,根据token获得用户的数据,并将新生成的文件名写入数据库中。

前端

<el-upload ref="upload" class="upload-demo" action="http://localhost:8181/user/uploadAvatar"
        :on-success="onSuccess" :on-preview="handlePreview" :auto-upload="false" :with-credentials="true"
        list-type="picture">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
      </el-upload>

 

onSuccess(response, file, fileList) {
        // data:
        //   newName: "e669f501-d74b-49c1-be73-0d9f0f6fb5c1.jpg";
        //   oldName: "88c751111ec1c00e1fd64b0ee41fd68f335b5fc2.jpg@404w_404h[1].jpg";
        // msg: "上传成功";
        // status: 200;
        this.$message.success(response.msg);
        this.$store.commit("setAvatar", response.data.newName);
        this.avatarUrl =
          "http://localhost:8181/user/file/avatar/" + response.data.newName;
        // console.log(file);
        // console.log(fileList);
      },
      handlePreview(file) {
        // console.log(file);
        // console.log(file.response.url);
        // window.open(file.response.url);
      },
      submitUpload() {
        this.$nextTick(() => {
          this.uploadVisible = false;
          this.$refs.upload.submit();
        });
      },

后端

controller:

@PostMapping("/user/uploadAvatar")
    public Result uploadFile(MultipartFile file,HttpServletRequest req) {
        String realPath = "D:\\CoolCatFile\\Avatar";

        return userService.uploadAvatar(file,req,realPath);
    }

service:

@Override
    public Result uploadAvatar(MultipartFile file, HttpServletRequest req,String realPath) {
     //本地存储的路径 Result result
= FileUtil.uploadFile(file,req,realPath); User user = findByToken(TokenUtil.getRequestToken(req,"user_token")); if (user.getUser_photoSrc() != null) FileUtil.deleteFile(user.getUser_photoSrc()); Map<String,String> map = (Map<String,String>)result.getData(); user.setUser_photoSrc(realPath + "\\" + map.get("newName")); update(user); return result; }

fileUtil:

public class FileUtil {
    public static Result uploadFile(MultipartFile file, HttpServletRequest req, String realPath) {
        Result result = new Result();

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + "." + getExtension(file);
        try {
            file.transferTo(new File(folder, newName));
            result.setStatus(200);
            result.setMsg("上传成功");
            Map<String,String> map = new HashMap<>();
            map.put("newName",newName);
            map.put("oldName",oldName);
            result.setData(map);
        } catch (IOException e) {
            result.setStatus(400);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
//                System.out.println("删除单个文件" + fileName + "成功!");
                return true;
            } else {
//                System.out.println("删除单个文件" + fileName + "失败!");
                return false;
            }
        } else {
//            System.out.println("删除单个文件失败:" + fileName + "不存在!");
            return false;
        }
    }

    public static String getExtension(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = null;
        if (fileName == null) {
            return null;
        } else {
            int index = indexOfExtension(fileName);
            extension = index == -1 ? "" : fileName.substring(index + 1);
        }

        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(file.getContentType());
        }
        return extension;
    }

    public static int indexOfExtension(String filename) {
        if (filename == null) {
            return -1;
        } else {
            int extensionPos = filename.lastIndexOf(46);
            int lastSeparator = indexOfLastSeparator(filename);
            return lastSeparator > extensionPos ? -1 : extensionPos;
        }
    }

    public static int indexOfLastSeparator(String filename) {
        if (filename == null) {
            return -1;
        } else {
            int lastUnixPos = filename.lastIndexOf(47);
            int lastWindowsPos = filename.lastIndexOf(92);
            return Math.max(lastUnixPos, lastWindowsPos);
        }
    }
}

MimeTypeUtils:

class MimeTypeUtils {
    public static final String IMAGE_PNG = "image/png";

    public static final String IMAGE_JPG = "image/jpg";

    public static final String IMAGE_JPEG = "image/jpeg";

    public static final String IMAGE_BMP = "image/bmp";

    public static final String IMAGE_GIF = "image/gif";

    public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"};

    public static final String[] FLASH_EXTENSION = {"swf", "flv"};

    public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg",
            "asf", "rm", "rmvb"};

    public static final String[] DEFAULT_ALLOWED_EXTENSION = {
            // 图片
            "bmp", "gif", "jpg", "jpeg", "png",
            // word excel powerpoint
            "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",
            // 压缩文件
            "rar", "zip", "gz", "bz2",
            // pdf
            "pdf"};


    public static String getExtension(String prefix) {
        switch (prefix) {
            case IMAGE_PNG:
                return "png";
            case IMAGE_JPG:
                return "jpg";
            case IMAGE_JPEG:
                return "jpeg";
            case IMAGE_BMP:
                return "bmp";
            case IMAGE_GIF:
                return "gif";
            default:
                return "";
        }
    }
}

Request:

public class Result implements Serializable {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 响应业务状态
    private Integer status;

    // 响应消息
    private String msg;

    // 响应中的数据
    private Object data;

    public static Result build(Integer status, String msg, Object data) {
        return new Result(status, msg, data);
    }

    public static Result ok(Object data) {
        return new Result(data);
    }

    public static Result ok() {
        return new Result(null);
    }

    public Result() {

    }

    public static Result build(Integer status, String msg) {
        return new Result(status, msg, null);
    }

    public Result(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public Result(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    /**
     * 将json结果集转化为Result对象
     *
     * @param jsonData
     *            json数据 传的是Result的对象的Json字符串
     * @param clazz
     *            TaotaoResult中的object类型
     * @return
     */
    public static Result formatToPojo(String jsonData, Class<?> clazz) {
        try {
            if (clazz == null) {
                return MAPPER.readValue(jsonData, Result.class);
            }
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (clazz != null) {
                if (data.isObject()) {
                    obj = MAPPER.readValue(data.traverse(), clazz);
                } else if (data.isTextual()) {
                    obj = MAPPER.readValue(data.asText(), clazz);
                }
            }
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 没有object对象的转化
     *
     * @param json
     * @return
     */
    public static Result format(String json) {
        try {
            return MAPPER.readValue(json, Result.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Object是集合转化
     *
     * @param jsonData  传的是Result的对象的Json字符串
     *            json数据
     * @param clazz
     *            集合中的类型
     * @return
     */
    public static Result formatToList(String jsonData, Class<?> clazz) {
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (data.isArray() && data.size() > 0) {
                obj = MAPPER.readValue(data.traverse(),
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

}

 图片显示

前端:

 <el-avatar :size="200" :src="avatarUrl"></el-avatar>
this.avatarUrl =
                  "http://localhost:8181/user/file/avatar/" +
                  _this.$store.getters.avatar;

后端

WebConfig

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //"/user/file/avatar/**"请求的路径,"\\CoolCatFile\\Avatar\\"映射的本地路径
        registry.addResourceHandler("/user/file/avatar/**").addResourceLocations("file:D:" + "\\CoolCatFile\\Avatar\\");
    }
}

例子:http://localhost:8181/user/file/avatar/25546f54-e9dd-4006-b365-e84f85fd92e6.jpg

posted @ 2021-04-13 16:28  EA2218764AB  阅读(1068)  评论(0编辑  收藏  举报