项目作者: chenshi011

项目描述 :
Android基于NanoHTTPD作为服务器的WiFi传书,其中NanoHTTPD很方便部署一个微型的服务器,前端上传文件的js也适合用于其他地方,除了非HTML5不能批量上传基本兼容性做到了
高级语言: Java
项目地址: git://github.com/chenshi011/AndroidWiFiTransfer.git


WIFI传书

  • 手机端的HttpServer采用开源项目NanoHttpd实现的。
    针对NanoHttpd,其中org.nanohttpd.protocols.http.progress下面的内容为我添加的上传进度用的,原生的NanoHttpd并没有上传进度,UploadFile是更改了TempFile存储临时文件的过程,直接存到指定的目录下面。
    如果要使用原生的方式,注释掉HttpServer中的下面这句即可(也推荐使用这种方式)
    1. setTempFileManagerFactory(new UploadFileManagerFactory());
    上传文件的Dispatcher部分可以看出,HTTPProgressSession是为了支持上传进度而稍微改动了HTTPSession:
    1. public Response handle(IHTTPSession session) {
    2. Map<String, String> files = new HashMap<String, String>();
    3. try {
    4. session.parseBody(files);
    5. } catch (IOException e) {
    6. e.printStackTrace();
    7. return Response.newFixedLengthResponse("Internal Error IO Exception: " + e.getMessage());
    8. } catch (ResponseException e) {
    9. e.printStackTrace();
    10. return Response.newFixedLengthResponse(e.getStatus(), NanoHTTPD.MIME_PLAINTEXT, e.getMessage());
    11. }
    12. if (!files.isEmpty()) {
    13. if (!(session instanceof HTTPProgressSession)) {
    14. Map<String, List<String>> params = session.getParameters();
    15. for (Entry<String, List<String>> entry : params.entrySet()) {
    16. final String paramsKey = entry.getKey();
    17. final List<String> fileNames = entry.getValue();
    18. final String tmpFilePath = files.get(paramsKey);
    19. if (!TextUtils.isEmpty(tmpFilePath)) {
    20. String fileName = paramsKey;
    21. if (fileNames != null && fileNames.size() > 0) {
    22. fileName = fileNames.get(fileNames.size() - 1);
    23. }
    24. final File tmpFile = new File(tmpFilePath);
    25. File dir = new File(Environment.getExternalStorageDirectory() + File.separator + DIR_IN_SDCARD);
    26. if (!dir.exists()) {
    27. dir.mkdirs();
    28. }
    29. final File targetFile = new File(dir, fileName);
    30. try {
    31. copyFile(tmpFile, targetFile);
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. }
    37. }
    38. return Response.newFixedLengthResponse("ok");
    39. }
    40. return Response.newFixedLengthResponse("404");
    41. }
  • 网页端采用jQuery实现,文件上传采用XmlHttpRequest、jquery.form、ajax三种方式混合使用的。

手机端截图

网页版截图

说明

基于NanoHTTPD做了细微的更改,都是添加文件的方式,没有直接更改库文件。
使用HTML5浏览器,文件进度是前端xhr的进度(支持批量上传);
使用非HTML5浏览器(如IE7/IE8/IE9)时候,文件上传进度是根据ajax获取的后台进度(不支持批量上传)。

如果使用java工程的话,直接在main函数里面初始化httpServer然后start即可。