springbootのファイルアップロードメソッド

springbootのファイルアップロードメソッド

Springboot を作成するプロジェクトでは、常にいくつかのファイル アップロード シナリオが含まれるため、選択のためのファイル アップロードの方法をここに示します。多くの説明は省略します。コードを参照してください (doge)

    @Autowired
    private MyFileService myFileService;

    @RequestMapping("/upload")
    public JsonResoult<MyFile> uploadFile(@RequestParam("file") MultipartFile file,
                                          @RequestParam("contentid") String contentid,
                                          @RequestParam("contenttype") String contenttype){
        //在保存文件之前对文件做检查
        //判断文件是否为空
        if (file.isEmpty()){
            throw new IFileEmptyException("上传文件为空,上传失败");
        }

        //判断文件是否超过限制
        if (file.getSize() >Integer.valueOf(100000000) ){
            throw new IFileSizeException("文件过大,上传失败");
        }

        //判断上传的文件是否为图片类型 file.getContentType()获取的是这种形式 --> text/html
        if (!file.getContentType().contains(file.getContentType())){
            throw new IFileTypeNotMatchException("文件类型不符,上传失败");
        }

        //获取上传文件的原始名字
        String originalFilename = file.getOriginalFilename();

        //获取文件的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用时间戳为文件定义新的名字
        String uuidName = Timer.getTimeStamp().toString();

        //定义文件最终的名字
        String fileName = uuidName + suffix;

        //获取项目在服务器上的真实位置并拼凑文件最终的保存位置
        String realPath = System.getProperty("user.dir") + "/src/main/resources/static/upload/" + fileName;

        /**
         * 这里其实有两个选择:①直接将文件写入硬盘 这里选择这种
         * ②先获取存储文件的文件夹的路径,判断存储文件的文件夹是否存在,不存在则创建
         * 最后再将文件名和文件夹路径进行拼凑出最终文件的保存路径
         **/
        //虚拟创建目标文件
        File destFile = new File(realPath);

        //获取目标文件的上级目录
        File parentFile = destFile.getParentFile();

        if (!parentFile.exists()){
            //代表文件的上级目录不存在,进行创建
            parentFile.mkdirs();
        }

        //选择第一种方法,直接写入目标位置
        try {
            file.transferTo(destFile);
        }catch (IFileStatusException e) {
            throw new IFileStatusException("文件状态异常,写入失败");
        }catch (IOException e) {
            throw new IFileUploadIOException("服务器或数据库写入文件失败");
        }



        //将文件的下载路径写入数据库
        String fileAccessPath = "/upload/" + fileName;

        MyFile myFile = new MyFile();
        String id  = Timer.getTimeStamp().toString();

        myFile.setId(id);
        myFile.setStatus("1");
        myFile.setType(suffix.substring(1,suffix.length()));
        myFile.setUrl(fileAccessPath);
        myFile.setContentid(contentid);
        myFile.setContenttype(contenttype);
//        写入数据库
       if(myFileService.upLoadFile(myFile)){
           return new JsonResoult<MyFile>(ServerStatus.SUCCESS,"",myFile);
       }
        return new JsonResoult<MyFile>(ServerStatus.Fail);

    }

 

おすすめ

転載: blog.csdn.net/qq_35889508/article/details/128160801