使用FileUtils類寫文件

maven依賴:

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.6</version>
</dependency>

使用示例:

FileUtils.writeByteArrayToFile(new File(filePath),files.getBytes());

備註: filePath爲目標文件名(全路徑),files爲源文件

附上微信小程序上傳mp3文件的後臺接口:

@RequestMapping(value = "/upload",produces = "application/json")
    public JsonResponse uploadAudio(HttpServletRequest request,
                                    @RequestParam("file") MultipartFile files){
        //錄音文件存儲路徑
        //String uploadPath  = "/home/developer/data/audio";
        String uploadPath  = "D:\\data\\devdata\\dialectStudy\\audio";
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }
        //獲取文件的擴展名
        String oldName = files.getOriginalFilename();
        String extensionName = ".mp3";
        // 獲取原來的擴展名
        if ((oldName != null) && (oldName.length() > 0)) {
            int dot = oldName.lastIndexOf('.');
            if ((dot > -1) && (dot < (oldName.length() - 1))) {
                extensionName = oldName.substring(dot);
            }
        }
        //構建文件名
        String fileName = "test" + extensionName;
        System.out.println("最終文件名:" + fileName);
        //文件全路徑
        String filePath = uploadPath + File.separatorChar + fileName;
        System.out.println("文件全路徑:" + filePath);
        //存儲到服務器
        try {
            FileUtils.writeByteArrayToFile(new File(filePath),files.getBytes());
        }catch (Exception e){
            System.out.println("write  audio file exception happened");
            System.out.println(e);
            return JsonResponse.newError("error happen");
        }
        return JsonResponse.newOk(filePath);
    }

備註:JsonResponse爲自定義類,可自行修改爲其他的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章