常用工具类--上传文件

文件上传

   将文件上传至服务器,然后通过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<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        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();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值