Java网络中间层---上传文件与上传多文件

网络库AppNetwork设计

最近开始研发和设计基础库相关工作,目前选择第一个封装的的库是 网络库 详情看Android基础库设计

目前支持aar导入,后期支持jar导入
目前先用指定url的仓库地址,后面放入JCenter

 repositories {
     maven {
       url 'https://dl.bintray.com/appmodular/maven/'
    }
 }

在library gradle配置文件中:

dependencies {
 testCompile 'junit:junit:4.8.2'
 compile 'com.alphabet.app:app_network:+'
}

技术选型

  • Retrofit+Okhttp+RxJava
  • 中间层(利用接口隔离,后期好扩展)
    你可以选择利用Okhttp,HttpClient ,HttpUrlConnection,Volley等其它任何网络框架来实现接口方法,完成网络请求任务
  • 支持Android 和其它Java程序使用
  • 服务器接口采用的是SpringBoot框架开发

全面初始化

 public static final String BASE_URL = "http://192.168.253.200:8080/Chapter/";

public static HttpClient httpClient = new HttpClient.Builder(BASE_URL)// 根路径
        .header("Cookie", "abdclejdldj82jk23jfjd")// 全局请求头 //局部可累加
        .header("Cache-control", "max-age=600")
        .maxRetryCount(0)// 局部可覆盖
        .isDebug(true)// 局部可覆盖
        .retryTimeout(1000)// 局部可覆盖
        .cacheFile(new File("C:/Cache"))// 局部可覆盖
        .cacheFileSize(10240 * 1024)// 局部可覆盖
        .cacheType(CacheType.ONLY_NETWORK)// 局部可覆盖
        .cacheTime(60 * 200)// 设置10分钟 //局部可覆盖
        .connectTimeout(5000)// 局部可覆盖
        .readTimeout(5000)// 局部可覆盖
        .writeTimeout(7000)// 局部可覆盖
        .httpBase(RetrofitImpl.getInstance())// 局部可覆盖
        .build(true);// 保持单例      

简单初始化

  HttpClient httpClient=new HttpClient.Builder(BASE_URL).build();

二次修改

 //默认非单例
 httpClient = httpClient.newBuilder().url("http://message.ubtob.com/").build();
  或者
 //保持单例
 httpClient.newBuilder().url("http://message.ubtob.com/").build(true);

上传单文件

    File f1 = new File("C://Users//Arison//Downloads//SmartAdmin_1_3.zip");
    httpClient.newBuilder().isDebug(true).build(true);
    //httpClient=httpClient.newBuilder().isDebug(true).build();
    httpClient.Api().send(
            new HttpClient.Builder()
                    .url("uploadFiles")
                    .add("file1", f1)
                    .add("phone", "1234567890")
                    .filesKey("file")
                    .method(Method.POST)
                    .build(),
            new NetResquestSubscriber<>(new SubscriberOnNextListener() {

                @Override
                public void onNext(Object t) {

        
                }
            }));
 
 

上传多文件

    File f1 = new File("C://Users//Arison//Downloads//SmartAdmin_1_3.zip");
    File f2 = new File("C://Users//Arison//Downloads//RetrofitWrapper.java");
    File f3 = new File("C://Users//Arison//Downloads//BaiduTranslate_chrome_1.2.crx");
    httpClient.Api().send(
            new HttpClient.Builder()
                    .url("uploadFiles")
                    .add("file1", f1)
                    .add("file2", f2)
                    .add("file3", f3)
                    .add("phone", "1234567890")
                    .filesKey("file")
                    .method(Method.POST)
                    .build(),
            new NetResquestSubscriber<>(new SubscriberOnNextListener() {

                @Override
                public void onNext(Object t) {

            
                }
            }));
 
 

服务器接口程序

/**
 * 单文件上传
 * 
 * @param request
 * @param mulits
 *        MultipartHttpServletRequest multiReq,
 */
@RequestMapping(value = "/uploadSigleFile", method = RequestMethod.POST)
public String uploadFile(HttpServletRequest request, @RequestParam MultipartFile file) {
    FileOutputStream fos;
    FileInputStream fs;
    System.out.println("文件名:" + file.getOriginalFilename());
    // 需要存放文件资源的路径,可以自由选择设置
    String filePath = "C://Users//Arison//Desktop//" + file.getOriginalFilename();
    filePath = request.getServletContext().getRealPath("/") + file.getOriginalFilename();
    try {
        fos = new FileOutputStream(new File(filePath));
        fs = (FileInputStream) file.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fs.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        fs.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return filePath;
}

/**
 * 单文件上传
 * 
 * @param request
 * @param mulits
 * @RequestParam MultipartHttpServletRequest file 直接放入控制器参数中,需要处理
 */
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFile2(HttpServletRequest request) {
    FileOutputStream fos;
    FileInputStream fs;
    MultipartFile file1 = ((MultipartHttpServletRequest) request).getFile("file");
    // MultipartFile file1=file.getFile("file");
    System.out.println("文件名:" + file1.getOriginalFilename());
    // 需要存放文件资源的路径,可以自由选择设置
    String filePath = "C://Users//Arison//Desktop//" + file1.getOriginalFilename();
    filePath = request.getServletContext().getRealPath("/");
    try {
        fos = new FileOutputStream(new File(filePath));
        fs = (FileInputStream) file1.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fs.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        fs.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return filePath;
}

/**
 * 多文件上传
 * 
 * @desc 使用MultipartHttpServletRequest
 * @param request
 * @param mulits
 */
@RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
public @ResponseBody Map uploadFiles(HttpServletRequest request) {
    List files = ((MultipartHttpServletRequest) request).getFiles("file");
    MultipartFile file = null;
    BufferedOutputStream stream = null;
    Map result = new HashMap<>();
    result.put("params", HttpRequestUtils.getHttpMessage(request));
    File f = new File("src/main/resources/uploads/");
    String path = f.getAbsolutePath();
    if (files == null) {
        result.put("msg", "upload failed  file param lost!");
        return result;
    }
    for (int i = 0; i < files.size(); ++i) {
        file = files.get(i);
        System.out.println("上传保存路径:" + file.getOriginalFilename());
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                stream = new BufferedOutputStream(
                        new FileOutputStream(new File(path + "/" + file.getOriginalFilename())));
                stream.write(bytes);
                stream.close();

            } catch (Exception e) {
                stream = null;
                result.put("msg", "You failed to upload " + i + " => " + e.getMessage());
                return result;
            }
        } else {
            result.put("msg", "You failed to upload " + i + " because the file was empty.");
            return result;
        }
    }
    result.put("msg", "upload sucess!");
    return result;
}

/**
 * 多文件上传
 * 
 * @desc 使用MultipartHttpServletRequest
 * @param request
 * @param mulits
 */
@RequestMapping(value = "/uploadMulitFiles", method = RequestMethod.POST)
public @ResponseBody Map uploadFiles2(HttpServletRequest request, @RequestParam MultipartFile[] file) {
    MultipartFile file1 = null;
    BufferedOutputStream stream = null;
    Map result = new HashMap<>();
    result.put("params", HttpRequestUtils.getHttpMessage(request));
    File f = new File("src/main/resources/uploads/");
    String path = f.getAbsolutePath();
    if (file == null) {
        result.put("msg", "upload failed  file param lost!");
        return result;
    }
    for (int i = 0; i < file.length; ++i) {
        file1 = file[i];
        System.out.println("上传保存路径:" + file1.getOriginalFilename());
        if (!file1.isEmpty()) {
            try {
                byte[] bytes = file1.getBytes();
                stream = new BufferedOutputStream(
                        new FileOutputStream(new File(path + "/" + file1.getOriginalFilename())));
                stream.write(bytes);
                stream.close();

            } catch (Exception e) {
                stream = null;
                result.put("msg", "You failed to upload " + i + " => " + e.getMessage());
                return result;
            }
        } else {
            result.put("msg", "You failed to upload " + i + " because the file was empty.");
            return result;
        }
    }
    result.put("msg", "upload sucess!");
    return result;
}

联系方式

  • QQ群:151909524 (Java或者Android)

你可能感兴趣的:(Java网络中间层---上传文件与上传多文件)