文件上傳

配置文件配置baseUrl

文件 params.properties配置,此路徑的絕對路徑為:E:/home/gscq073240j/myfile/temp_qbs5/ (E盤為項(xiàng)目所在的磁盤)


圖片.png

在初始化類中配置不同文件保存的不同的文件夾

@Component
@PropertySource("classpath:conf/params.properties")
public class FileUploadPathConfig {

    @Value("${baseFilePath}")
    String basePath;

    public static String UPLOAD_PATH = null;

    public static String IMG_PATH = null;

    public static String VIDEO_PATH = null;

    public static String AUDIO_PATH = null;

    public static String TYPE_PATH = null;

    public static String EXCEL_PATH = null;

    public static String TYPE_TEMPLATE = null;

    public static String QUESTION_PATH = null;

    public static String QUESTION_EXCEL_PATH = null;

    public static String QUESTION_EXCEL_TEMPLATE = null;

    public static String QUESTION_EXCEL_TEMP_PATH = null;

    public static String QUESTION_FILE = null;



    @PostConstruct
    void init() {
        UPLOAD_PATH = basePath;
        IMG_PATH = UPLOAD_PATH + "img/";
        VIDEO_PATH = UPLOAD_PATH + "video/";
        AUDIO_PATH = UPLOAD_PATH + "audio/";
        TYPE_PATH = UPLOAD_PATH + "type/";
        EXCEL_PATH = TYPE_PATH + "excel/";
        TYPE_TEMPLATE = TYPE_PATH + "type_template__.xls";
        QUESTION_PATH = UPLOAD_PATH + "question/";
        QUESTION_EXCEL_PATH = QUESTION_PATH + "excel/";
        QUESTION_EXCEL_TEMPLATE = QUESTION_EXCEL_PATH + "question_template__.xlsx";
        QUESTION_EXCEL_TEMP_PATH = QUESTION_EXCEL_PATH + "temp/";
        QUESTION_FILE = QUESTION_PATH + "file/";
    }

}

配置之后圖片的保存路徑為:/home/gscq073240j/myfile/temp_qbs5/img/

圖片上傳接口:

@ResponseBody
    @PostMapping(value = "/fileUpload")
    public Result fileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        File aa = new File(FileUploadPathConfig.IMG_PATH ) ;
        if (!new File(FileUploadPathConfig.IMG_PATH).exists()){
            new File(FileUploadPathConfig.IMG_PATH).mkdirs();
        }
        if (file.isEmpty()) {
            return ResultFactory.buildFailResult("文件為空");
        }
        String filePath = null, returnPath = null, suffixName = null;
        try {
            byte[] b = new byte[4];
            file.getInputStream().read(b, 0, b.length);
            String type = bytesToHexString(b).toUpperCase();
            if (type.contains("0000001C") || type.contains("00000020")) {
                //視頻文件
                filePath = FileUploadPathConfig.VIDEO_PATH;
                returnPath = "/upload/video/";
                suffixName = ".mp4";
            } else if (type.contains("FFD8FFE0")) {
                // 圖片格式
                filePath = FileUploadPathConfig.IMG_PATH;
                returnPath = "/upload/img/";
                BufferedImage image = ImageIO.read(file.getInputStream());
                if (image != null) {
                    if (image.getWidth() == 0) {
                        return ResultFactory.buildFailResult("圖片格式不規(guī)范!");
                    }
                    if (file.getSize() > 1 * 1024 * 200) {
                        return ResultFactory.buildFailResult("小于200KB的照片才允許上傳!");
                    }
                } else {
                    return ResultFactory.buildFailResult("圖片格式不規(guī)范!");
                }
                suffixName = ".jpg";
            } else if (type.contains("49443304")) {
                // 音頻文件
                filePath = FileUploadPathConfig.AUDIO_PATH;
                returnPath = "/upload/audio/";
                suffixName = ".mp3";
            } else {
                return ResultFactory.buildFailResult("不支持上傳文件格式");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String fileContentType = file.getContentType();
        String fileName = file.getOriginalFilename();  // 文件名
//         suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后綴名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        String absolutePath = new File(filePath).getAbsolutePath();
        File dest = new File(new File(filePath).getAbsolutePath()+"/"+ fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
//        FileOutputStream out = new FileOutputStream(fileName);
//        out.write(file.getBytes());
//        out.flush();
//        out.close();
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultFactory.buildFailResult(e.getMessage());
        }
        return ResultFactory.buildSuccessResult(returnPath + fileName);
    }

返回的圖片路徑為 //upload/img/+uuid的值.jpg ,但是實(shí)際圖片存放的路徑為E:/home/gscq073240j/myfile/temp_qbs5/img/uuid的值.jpg.
項(xiàng)目的頁面樣式為


圖片.png

圖片此時的回顯


圖片.png

訪問的路徑如上圖。

所以需要配置靜態(tài)資源訪問路徑:

@Configuration
public class SpringWebMvcConfigurer extends WebMvcConfigurationSupport {
    /**
     * 配置靜態(tài)訪問資源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
      /*  String p = new File(path).getAbsolutePath() + File.separator;//取得在服務(wù)器中的絕對路徑
        System.out.println("Mapping /upload/** from " + p);
        registry.addResourceHandler("/upload/**") // 外部訪問地址
                .addResourceLocations("file:" + p)// springboot需要增加file協(xié)議前綴
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 設(shè)置瀏覽器緩存30分鐘*/
        // 覆蓋默認(rèn)配置,自定義
        registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ FileUploadPathConfig.UPLOAD_PATH);
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/", "classpath:/static/static/");
        super.addResourceHandlers(registry);
    }
}

此時圖片就能回顯了。

添加用戶,保存包數(shù)據(jù)庫

控制層:
/**
     * 新增專家用戶
     * @param userModel
     * @return
     */
    @RequestMapping(value = "/addUser")
    @ResponseBody
    public Result addUser(@RequestBody UserModel userModel) {
        return userService.addUser(userModel);
    }
service層
@Override
    @Transactional(rollbackFor = Exception.class)
    public Result addUser(@RequestBody UserModel userModel) {
        UserEntity userEntity = userModel.prototype();  //model類轉(zhuǎn)實(shí)體類
        try {
            userEntity.setCardIdPath(FileUtils.nomenclator(userEntity.getCardId(),
                    FileUploadPathConfig.IMG_PATH + userEntity.getCardIdPath().replace(userModel.getBaseUrl(),
                            ""), UserEntity.CARDID_FRONT));
            userEntity.setCardIdPathBack(FileUtils.nomenclator(userEntity.getCardId(),
                    FileUploadPathConfig.IMG_PATH + userEntity.getCardIdPathBack().replace(userModel.getBaseUrl(),
                            ""), UserEntity.CARDID_BACK));
            userEntity.setProfessionalPath(FileUtils.nomenclator(userEntity.getCardId(),
                    FileUploadPathConfig.IMG_PATH + userEntity.getProfessionalPath().replace(userModel.getBaseUrl(),
                            ""), UserEntity.PROFESSIONAL));
            userEntity.setQualificationCertificatePath(FileUtils.nomenclator(userEntity.getCardId(),
                    FileUploadPathConfig.IMG_PATH + userEntity.getQualificationCertificatePath().replace(userModel.getBaseUrl(),
                            ""), UserEntity.QUALIFICATION));
        } catch (IOException e) {
            e.printStackTrace();
        }
        userMapper.insertSelective(userEntity);
        return ResultFactory.buildSuccessResult(null);
    }

nomenclator 方法

將存入數(shù)據(jù)庫的值/upload/img/uuid的值.jpg改為/upload/img/身份證號.jpg,并將文件夾中實(shí)際的圖片的文件名renameto(文件移動)為身份證號.jpg


圖片.png
public class FileUtils {
    public static String nomenclator(String cardId, String path, String name) throws IOException {

        String replace = path.replace("/upload/img/", "");
        File file = new File(replace);
        if (!file.exists()) {
            file.createNewFile();
        }
        String parent = file.getParent(); //根路徑
        String suffixName = file.getName().substring(file.getName().lastIndexOf("."));
        String s = parent + File.separator + cardId + "_" + name + suffixName;
        File newFile = new File(s);
        if (newFile.exists() && newFile.isFile()) {
            newFile.delete();
        }
        File f = new File(s);
        if (file.renameTo(f)) {
            String aa = "/upload/img/" + f.getName();
            return "/upload/img/" + f.getName();
        }
        return null;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • feisky云計(jì)算、虛擬化與Linux技術(shù)筆記posts - 1014, comments - 298, trac...
    不排版閱讀 4,353評論 0 5
  • WEB安全漏洞中,與文件操作相關(guān)的漏洞類型就不少,在大部分的滲透測試過程中,上傳文件(大、小馬)是必不可少的一個流...
    CanMeng閱讀 634評論 1 7
  • 原文地址:https://xz.aliyun.com/t/6357 1. 文件上傳漏洞 1.1 漏洞簡介 ? 文件...
    這是什么娃哈哈閱讀 1,890評論 0 0
  • 在火車上搖搖晃晃地敲下這些字! 今天在群里看見了一個小伙伴寫的文章,關(guān)于肥胖的人被歧視的話題,猛然就想到了那天下午...
    心若水容萬物閱讀 306評論 0 1
  • 有時候 我想做你爸爸 告訴你: 如果我是你爸爸 在你很小的時候 我會每天抱著你 給你講故事?lián)Q尿布搭積木 好好疼愛你...
    千鳥和她閱讀 317評論 0 1

友情鏈接更多精彩內(nèi)容