nanoHTTPD 接收 okhttp 上传的文件
来源:互联网 发布:淘宝金币有什么用 编辑:程序博客网 时间:2024/05/01 11:12
Explained before, the client use okhttp upload a file just like the follow code
RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) //sourceFile is a File as you know .addFormDataPart("image_file_1", "logo-square1.png", RequestBody.create(MediaType.parse("image/png"), sourceFile)) .build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Response response = client.newCall(request).execute();
The following code is just what you want:
@Override public Response serve(IHTTPSession session) { Method method = session.getMethod(); // ▼ 1、parse post body ▼ Map<String, String> files = new HashMap<>(); if (Method.POST.equals(method) || Method.PUT.equals(method)) { try { session.parseBody(files); } catch (IOException ioe) { return getResponse("Internal Error IO Exception: " + ioe.getMessage()); } catch (ResponseException re) { return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage()); } } //after the body parsed, by default nanoHTTPD will save the file to cache and put it into params( "image_file_1" as key and the value is "logo-square1.png"); //files key is just like "image_file_1", and the value is nanoHTTPD's template file path in cache // ▲ 1、parse post body ▲ // ▼ 2、copy file to target path xiaoyee ▼ Map<String, String> params = session.getParms(); for (Map.Entry<String, String> entry : params.entrySet()) { final String paramsKey = entry.getKey(); if (paramsKey.contains("image_file_1")) { final String tmpFilePath = files.get(paramsKey); final String fileName = paramsKey; final File tmpFile = new File(tmpFilePath); final File targetFile = new File(mCurrentDir + fileName); LogUtil.log("copy file now, source file path: %s,target file path:%s", tmpFile.getAbsoluteFile(), targetFile.getAbsoluteFile()); //a copy file methoed just what you like copyFile(tmpFile, targetFile); //maybe you should put the follow code out return getResponse("Success"); } } // ▲ 2、copy file to target path xiaoyee ▲ return getResponse("Error 404: File not found"); }
本文为自己在博客的一个备份,我的原回答在:
https://stackoverflow.com/questions/28739744/nanohttpd-how-to-save-uploaded-file-to-sdcard-folder/43154040#43154040
author:xiaoyee
0 0
- nanoHTTPD 接收 okhttp 上传的文件
- OkHttp的post上传文件
- okhttp的请求+上传文件
- OkHttp使用+文件的上传+断点续传
- okhttp上传文件实例
- okhttp上传文件
- okhttp-上传文件
- okhttp封装文件上传
- okhttp上传文件
- OKhttp post上传文件
- okhttp方法上传图片和接收图片
- 接收浏览器上传文件的cgi程序
- 接收浏览器上传文件的cgi程序
- Http文件上传服务器端接收的数据格式
- Java服务器接收上传的文件
- OkHttp实现文件上传进度
- Okhttp文件上传源码分析
- okhttp 上传带参数文件
- Muli3D <4> Calculate vertex tangent
- 数据库调优
- Spark学习
- mxnet显示层参数代码
- ns-3 教程 —— 概念概述(第一个 ns-3 程序)
- nanoHTTPD 接收 okhttp 上传的文件
- ndk 编译opencv
- 装修的几个小贴士
- Mysql分页实现及优化
- ${pageContext.request.contextPath}JSP取得绝对路径
- ArcGIS api for JavaScript 4.3 学习笔记(0)本地Tomcat部署arcgis_js_api
- 本地存储和离线缓存
- 在阿里云上配置Apach Tomcat
- three.js 实现3D漫游