麟の随笔

  • 游戏
  • 影视
  • Tech
  1. 首页
  2. 科技
  3. Java
  4. 正文

Java 通过Post方式传输文件

2021年11月18日 1487点热度 1人点赞 0条评论

此方法可作为FTP备用

客户端

服务端使用时使用了Okhttp3,对于maven项目需要引用

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
    <version>4.8.1</version>
</dependency>

对于非maven的项目需要引用

  • okhttp-4.8.1.jar
  • okio-2.8.0.jar
  • kotlin-stdlib-1.3.72.jar

方法实现

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FileTransferUtil {
    public static final Logger log = LoggerFactory.getLogger(FileTransferUtil.class);
    public static String defaultUri = "192.168.1.18:8080/server/fileRecieve";//常量,目标服务器的系统接口
    public static String defaultRoot = "D:/";//目标服务器的根目录路径,类似于FTP的根目录

    /**
     * 传输文件
     * @param localFile 本地文件
     * @param romotUpLoadePath 远程目录
     * @return 结果
     * @date 2021年11月18日
     */
    public synchronized static boolean uploadFile(File localFile, String romotUpLoadePath) {
        try {
            // 如果uri和root都不为空
            if (ObjectUtils.isEmpty(defaultUri) || ObjectUtils.isEmpty(defaultRoot)) {
                log.info("传输对象和目标目录不能为空!");
                return false;
            }
            if (romotUpLoadePath.endsWith("/")) {
                romotUpLoadePath = romotUpLoadePath.substring(0, romotUpLoadePath.length() - 1);
            }
            String targetStr = romotUpLoadePath + "/" + localFile.getName();
            return transferFile(defaultUri, localFile.getAbsolutePath(), defaultRoot, targetStr);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 传输文件
     * @param urlStr 请求地址
     * @param localStr 本地文件绝对路径
     * @param rootStr 远程根目录
     * @param targetStr 目标目录
     * @return 结果
     * @date 2021年11月18日
     */
    public synchronized static boolean transferFile(String urlStr, String localStr, String rootStr, String targetStr) {
        try {
            // 拼接请求对象
            if (!urlStr.contains("?")) {
                urlStr += "?action=uploadFile";// 请求对象
                urlStr += "&target=" + targetStr;// 目标目录
                urlStr += "&root=" + rootStr;// 根目录
            }
            System.out.println(urlStr);
            OkHttpClient httpClient = new OkHttpClient();
            MediaType mediaType = okhttp3.MediaType.parse(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE);
            File sendFile = new File(localStr);
            RequestBody fileBody = RequestBody.create(mediaType, sendFile);
            RequestBody requestBody = new MultipartBody.Builder().addFormDataPart("file", sendFile.getName(), fileBody).build();
            Request request = new Request.Builder().post(requestBody).url(urlStr).addHeader("Content-Type", org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE).build();
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                if (response.code() == 204) {
                    log.info("文件上传成功..");
                }
                else {
                    log.error("文件上传失败..");
                    return false;
                }
            }
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 上传文件夹
     * @param localDirectory 文件将爱目录
     * @param remoteDirectoryPath 远程目录
     * @return 结果
     * @date 2021年11月18日
     */
    public static boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) {
        try {
            File src = new File(localDirectory);
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            System.out.println("本地路径 : " + localDirectory + ";目标路径:" + remoteDirectoryPath);
            File[] allFile = src.listFiles();
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    String srcName = allFile[currentFile].getPath().toString();
                    Thread.sleep(100L);
                    uploadFile(new File(srcName), remoteDirectoryPath);
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath);// 递归
                }
            }
            return true;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}

服务端

@RequestMapping(params = "action=uploadFile")
    @ResponseBody
    public void uploadFile(@RequestParam(value = "file", required = false) MultipartFile file, String target, String root, String token, HttpServletResponse response) {
        try {           

            String finalStr = ValidateUtil.isEmpty(root) ? target : root + target;// 当没有root时使用target作为绝对路径
            try {
                // 先创建父级文件夹
                File targetFile = new File(finalStr);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdirs();
                }
                // 保存
                file.transferTo(targetFile);
                System.out.println(finalStr);
            }
            catch (Exception e) {
                e.printStackTrace();
                return;
            }
            PrintWriter out = response.getWriter();
            out.print(this.getJson(true, ""));
        }
        catch (Exception e) {
            throw new BaseException(e, log);
        }
    }
标签: 暂无
最后更新:2021年11月18日

晓虎

必须有人浴血奋战,世上才有自由可言!

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2024 kirinz.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

闽ICP备19013981号