java http实现群晖NAS文件服务器资源管理

废话不多说,直接上代码

package com.ieds.back.infrastructure.util.oos;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ieds.back.domain.common.R;
import com.ieds.back.domain.enums.NasUploadResEnum;
import com.ieds.back.infrastructure.persistence.mybatis.vo.NasFileVO;
import com.ieds.back.infrastructure.util.log.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "NAS")
@RestController
@RequestMapping("/nas")
@Slf4j
public class NasFileUtils {

    private String nasUrl;

    private String account;
    private String passwd;
    private String parentFolder;
    private String localPath;
    private static HttpClient client = null;
    private String sid;


    /**
     *  获取主文件夹
     */
    public R getFolderAndFile(String pattern) {
        List<String> list = Arrays.stream(parentFolder.split(",")).filter(item -> StringUtils.isBlank(pattern) || item.startsWith(pattern)).collect(Collectors.toList());
        return R.ok(list);
    }


    /**
     *  获取文件夹及文件
     */
    public R getFolderAndFile(@RequestParam String path, String pattern) throws IOException {
        String folderStrEncode = URLEncoder.encode(path);
        String uri = nasUrl + "/query.cgi?api=SYNO.FileStation.List&method=list&version=2&folder_path=" + folderStrEncode + "&additional%3D%5B%22real_path%22%2C%22size%22%2C%22owner%22%2C%22time%2Cperm%22%2C%22type%22%5D";
        if (StringUtils.isNotBlank(pattern)) {
            uri += "&pattern=%22*" + pattern + "*%22";
        }
        //目录列表
        HttpGet get2 = new HttpGet(uri);
        HttpResponse response2 = client.execute(get2);
        log.info("SYNO.FileStation.List接口响应结果{}", response2.getEntity());
        JSONObject jsonObject2 = JSON.parseObject(EntityUtils.toString(response2.getEntity()));
        NasFileVO nasFileVO = JSONObject.parseObject(jsonObject2.get("data").toString(), NasFileVO.class);
        return R.ok(nasFileVO);
    }

    /**
     * 下载文件/文件夹(zip)
     * @param path
     * @param response
     * @throws IOException
     */
    public void download(String path, HttpServletResponse response) throws IOException {
    	client = getClient();
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        if (!fileName.contains(".")) {
            fileName += ".zip";
        }
        String folderStrEncode = URLEncoder.encode(path);
        String uri = nasUrl + "/entry.cgi?api=SYNO.FileStation.Download&version=2&method=download&path=" + folderStrEncode + "&mode=%22open%22";
        //目录列表
        HttpGet get2 = new HttpGet(uri);
        HttpResponse response2 = client.execute(get2);

        InputStream fis = response2.getEntity().getContent();
        byte[] buffer = readInputStream(fis);
        fis.read(buffer);
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));//处理中文乱码
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }


    /**
     * 上传文件
     * @param multipartFile
     * @param filePath
     * @param request
     * @return
     * @throws IOException
     */
    public R putFile(@RequestParam MultipartFile multipartFile, String filePath, HttpServletRequest request) throws IOException {
        String successFlag = "success";
        if (StringUtils.isEmpty(sid)) {
            getClient();
        }
        String fileName = multipartFile.getOriginalFilename();
        String serverUrl = nasUrl + "entry.cgi?api=SYNO.FileStation.Upload&version=2&method=upload&_sid=" + sid;
        String path = getJarPath() + "/" + localPath + "/" + System.currentTimeMillis() + "/" + fileName;
        File saveFile = new File(path);
        if (!saveFile.getParentFile().exists()) {
            saveFile.getParentFile().mkdirs();
        }
        FileCopyUtils.copy(multipartFile.getInputStream(), Files.newOutputStream(saveFile.toPath()));
        File newFile = new File(saveFile.getPath());
        Map<String, Object> map = new HashMap<>();
        map.put("filename", fileName);
        map.put("path", filePath);
        map.put("create_parents", false);
        map.put("file", newFile);
        String post = HttpUtil.post(serverUrl, map);
        JSONObject res = JSONObject.parseObject(post);
        //删除本地文件
        saveFile.delete();
        newFile.delete();
        if (res.containsKey(successFlag) && res.getBoolean(successFlag)) {
            return R.ok("上传成功!");
        } else {
            String errorStr = res.getString("error");
            JSONObject errorRes = JSONObject.parseObject(errorStr);
            log.info("上传失败,错误信息,{}", errorRes);
            return R.failed("上传失败!" + NasUploadResEnum.getValue(errorRes.getInteger("code")));
        }

    }

    /**
     * 获取文件详情
     * @param path
     * @param response
     * @return
     * @throws IOException
     */
    public R getInfo(String path, HttpServletResponse response) throws IOException {
        client = getClient();
        String folderStrEncode = URLEncoder.encode(path);
        String uri = nasUrl + "/entry.cgi?api=SYNO.FileStation.List&version=1&method=getinfo&path=" + folderStrEncode + "&additional=real_path,owner,time,perm";
        //目录列表
        HttpGet get2 = new HttpGet(uri);
        HttpResponse response2 = client.execute(get2);
        JSONObject jsonObject2 = JSON.parseObject(EntityUtils.toString(response2.getEntity()));
        JSONObject data = jsonObject2.getJSONObject("data");
        sid = data.getString("sid");
        return R.ok(jsonObject2);
    }


    /**
     * 从输入流中获取数据
     *
     * @param fis 输入流
     * @return
     * @throws Exception
     */
    private byte[] readInputStream(InputStream fis) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        //fis.close();此处一定不能关闭流
        return outStream.toByteArray();
    }

    /**
     * 获取httpClient
     * @return
     * @throws IOException
     */
    public HttpClient getClient() throws IOException {
        if (sid == null || client == null) {
            client = new DefaultHttpClient();
            // sid参数 &_sid=" + sid + "
            HttpGet get = new HttpGet(nasUrl + "/auth.cgi?api=SYNO.API.Auth&version=3&method=login&account=" + account + "&passwd=" + passwd + "&session=FileStation&format=cookie");
            HttpResponse response = client.execute(get);
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
            JSONObject data = jsonObject.getJSONObject("data");
            sid = data.getString("sid");
            log.info("NAS客户端登录返回结果----------,{}", data);
        }
        return client;
    }

    public String getJarPath() {
        String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        if (System.getProperty("os.name").contains("dows")) {
            path = path.substring(1, path.length()).replace("file:", "");
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            return path.substring(0, path.lastIndexOf("/")).replace("file:", "");
        }
        return path.replace("file:", "");
    }
}

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值