【java工具类】上传文件


    /**上传文件
     * @param file 文件
     * @param filePath 上传文件路径,不包含文件名
     * @param fileName 新的文件名
     * @return 返回一个路径名
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file, String filePath, String fileName) throws Exception {
        //原文件名
        String filename = file.getOriginalFilename();
        //获取文件后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        //判断目录是否为空,若为空新建目录
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //上传文件路径
        String path = filePath+"/"+fileName+suffix;
        //上传
        FileOutputStream out = new FileOutputStream(path);
        out.write(file.getBytes());
        out.flush();
        out.close();
        return path;
    }

调用:

    @ApiOperation("上传文件")
    @PostMapping(value = "/uploadFile", consumes = "multipart/*",headers = "content-type=multipart/form-data")
    @ResponseBody
    public void uploadFile(
            @RequestParam MultipartFile file)
            throws Exception {
        uploadFile(file,"G:/pic","123");
        try {

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM