使用FileUtils类写文件

maven依赖:


	commons-io
	commons-io
	2.6

使用示例:

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为自定义类,可自行修改为其他的

你可能感兴趣的:(工具使用,java项目,微信小程序)