文件上傳的幾種方式?

1、直接使用 file.transferTo();

String path = "";
if(!StringUtils.isNull(file)){
    String contentType = file.getContentType();
    // 獲得文件後綴
    String imageSux = contentType.substring(contentType.indexOf("/")+1);
    if(!(imageSux.equalsIgnoreCase("png") || imageSux.equalsIgnoreCase("jpg") || imageSux.equalsIgnoreCase("bmp") || imageSux.equalsIgnoreCase("jpeg") || imageSux.equalsIgnoreCase("gif"))){
        return new AjaxResult(ERROR,"請上傳正常的圖片文件");
    }

    String uuid = UUID.randomUUID().toString().replaceAll("-","");
    path = request.getSession().getServletContext().getRealPath("image");
    String filename = uuid + "." + imageSux;
    try {
        File targetFile = new File(path, filename);
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
            targetFile.createNewFile();
        }

        crmUser.setHeadPhoto(path + "\\" + filename);
        //寫入文件
        file.transferTo(targetFile);
    } catch (Exception e) {
        return new AjaxResult(ERROR,"上傳出現異常");
    }
}

2、JDK1.7以後,使用nio進行上傳;

if(!StringUtils.isNull(file)){
    try {
        byte[] bytes = file.getBytes();
        String contentType = file.getContentType();
        // 獲得文件後綴
        String imageSux = contentType.substring(contentType.indexOf("/")+1);
        if(!(imageSux.equalsIgnoreCase("png") || imageSux.equalsIgnoreCase("jpg") || imageSux.equalsIgnoreCase("bmp") || imageSux.equalsIgnoreCase("jpeg") || imageSux.equalsIgnoreCase("gif"))){
            return new AjaxResult(ERROR,"請上傳正常的圖片文件");
        }

        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String filename = uuid + "." + imageSux;

        Path path = Paths.get(UPLOAD_FOLDER + filename);
        //如果沒有files文件夾,則創建
        if (!Files.isWritable(path)) {
            Files.createDirectories(Paths.get(UPLOAD_FOLDER));
        }
        //文件寫入指定路徑
        Files.write(path, bytes);

        crmUser.setHeadPhoto(path.toString());
        logger.debug("文件寫入成功...");
    } catch (IOException e) {
        e.printStackTrace();
        return new AjaxResult(ERROR,"上傳出現異常");
    }
}

3、可以使用文件服務請求接口上傳 SpringBoot請求第三方接口方式

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章