常用工具类--上传文件

文件上传

   将文件上传至服务器,然后通过nginx访问
   其中localPath是服务器上文件保存地址,serverIp是文件访问路径

public static String upload(HttpServletRequest request, MultipartFile file, String localPath, String serverIp,Long fileNameCode) {

//        String basePath = request.getScheme() + "://" + serverIp + ":" + request.getLocalPort();//获取本地地址
        //String basePath = localUrl;//获取本地地址
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
        String fileName = file.getOriginalFilename();

        String uploadFilePath = localPath;

        String folder = DateUtil.dateToString(DateUtil.YYYYMM,new Date()) + "/";

        String tomonthDir = uploadFilePath + folder;//每月创建一个文件夹,方便管理文件

        File tempFile = new File(tomonthDir + fileNameCode + "." + suffix);


        File fileDir = new File(tomonthDir);

        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        try{
            InputStream is = file.getInputStream();
            // 开始保存文件到服务器
            if (!fileName.equals("")) {
                FileOutputStream fos = new FileOutputStream(tempFile);
                byte[] buffer = new byte[8192]; // 每次读8K字节
                int count = 0;
                // 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count); // 向服务端文件写入字节流
                }

//                file.transferTo(tempFile);

                changeFolderPermission(tempFile);//更改权限
                fos.close(); // 关闭FileOutputStream对象
                is.close(); // InputStream对象
            }
        } catch(Exception e) {
            throw new MessageException(e.getMessage());
        }

        return serverIp + folder + fileNameCode + "." + suffix;

    }

    /**
     * 设置文件权限
     * @param dirFile
     * @throws IOException
     */
    private static void changeFolderPermission(File dirFile) throws IOException {
        Set perms = new HashSet();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.OTHERS_READ);
        try {
            Path path = Paths.get(dirFile.getAbsolutePath());
            Files.setPosixFilePermissions(path, perms);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java,工具类)