畢設-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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM