【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 {
        FileUpload.uploadFile(file,"G:/pic","123");
        try {

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

        }
    }

猜你喜欢

转载自www.cnblogs.com/tuituji27/p/11346244.html
今日推荐