【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