nanoHTTPD 接收 okhttp 上传的文件

2 篇文章 0 订阅
1 篇文章 0 订阅

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

NanoHTTPD是一个免费、轻量级的(只有一个Java文件) HTTP服务器,可以很好地嵌入到Java程序中。支持 GET, POST, PUT, HEAD 和 DELETE 请求,支持文件上传,占用内存很小。可轻松定制临时文件使用和线程模型。NanoHTTPD for JDK 1.1https://github.com/NanoHttpd/nanohttpd/tree/nanohttpd-for-java1.1示例代码:package fi.iki.elonen.debug;   import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.ServerRunner;   import java.util.HashMap; import java.util.List; import java.util.Map;   public class DebugServer extends NanoHTTPD {     public DebugServer() {         super(8080);     }       public static void main(String[] args) {         ServerRunner.run(DebugServer.class);     }       @Override public Response serve(IHTTPSession session) {         Map<String, List<String>> decodedQueryParameters =             decodeParameters(session.getQueryParameterString());           StringBuilder sb = new StringBuilder();         sb.append("<html>");         sb.append("<head><title>Debug Server</title></head>");         sb.append("<body>");         sb.append("<h1>Debug Server</h1>");           sb.append("<p><blockquote><b>URI</b> = ").append(             String.valueOf(session.getUri())).append("<br />");           sb.append("<b>Method</b> = ").append(             String.valueOf(session.getMethod())).append("</blockquote></p>");           sb.append("<h3>Headers</h3><p><blockquote>").             append(toString(session.getHeaders())).append("</blockquote></p>");           sb.append("<h3>Parms</h3><p><blockquote>").             append(toString(session.getParms())).append("</blockquote></p>");           sb.append("<h3>Parms (multi values?)</h3><p><blockquote>").             append(toString(decodedQueryParameters)).append("</blockquote></p>");           try {             Map<String, String> files = new HashMap<String, String>();             session.parseBody(files);             sb.append("<h3>Files</h3><p><blockquote>").                 append(toString(files)).append("</blockquote></p>");         } catch (Exception e) {             e.printStackTrace();         }           sb.append("</body>");         sb.append("</html>");         return new Response(sb.toString());     }       private String toString(Map<String, ? extends Object> map) {         if (map.size() == 0) {             return "";         }         return unsortedList(map);     }       private String unsortedList(Map<String, ? extends Object> map) {         StringBuilder sb = new StringBuilder();         sb.append("<ul>");         for (Map.Entry entry : map.entrySet()) {             listItem(sb, entry);         }         sb.append("</ul>");         return sb.toString();     }       private void listItem(StringBuilder sb, Map.Entry entry) {         sb.append("<li><code><b>").append(entry.getKey()).             append("</b> = ").append(entry.getValue()).append("</code></li>");     } } 标签:NanoHTTPD
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

杨筱毅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值