引言:本来android文件上传的博客在网上挺多的,不过好些都只是有前台android端的上传,并没有后台服务器端的接收。而且自己写的时候也确实遇见了一些之前没注意到的地方,写出来也算是给自己提个醒。
我这里就不把全部的代码都贴出来了,就只贴一下核心代码就算了,如果有什么疑问或者不对的地方,欢迎指教。
我要做的是把我app的日志文件上传到指定服务器的功能。并没有写的太复杂,我参考鸿洋大神的博客的时候,看他对DataOutputStream写入了headinfo和endinfo,但是我没理解这样写的目的,所以也没加,如果有知道的可以告诉我呦。
废话不多说,直接上代码。
下面是android端上传文件代码:

    /**     * 上传文件到服务器     * @param context     * @param uploadUrl     上传服务器地址     * @param oldFilePath       本地文件路径     */    public static void uploadLogFile(Context context, String uploadUrl, String oldFilePath){        try {            URL url = new URL(path);              HttpURLConnection con = (HttpURLConnection)url.openConnection();            // 允许Input、Output,不使用Cache            con.setDoInput(true);            con.setDoOutput(true);            con.setUseCaches(false);            con.setConnectTimeout(50000);            con.setReadTimeout(50000);            // 设置传送的method=POST            con.setRequestMethod("POST");            //在一次TCP连接中可以持续发送多份数据而不会断开连接            con.setRequestProperty("Connection", "Keep-Alive");            //设置编码            con.setRequestProperty("Charset", "UTF-8");            //text/plain能上传纯文本文件的编码格式            con.setRequestProperty("Content-Type", "text/plain");            // 设置DataOutputStream            DataOutputStream ds = new DataOutputStream(con.getOutputStream());            // 取得文件的FileInputStream            FileInputStream fStream = new FileInputStream(oldFilePath);            // 设置每次写入1024bytes            int bufferSize = 1024;            byte[] buffer = new byte[bufferSize];            int length = -1;            // 从文件读取数据至缓冲区            while ((length = fStream.read(buffer)) != -1) {                // 将资料写入DataOutputStream中                ds.write(buffer, 0, length);            }            ds.flush();            fStream.close();            ds.close();            if(con.getResponseCode() == 200){                logger.info("文件上传成功!上传文件为:" + oldFilePath);            }        } catch (Exception e) {            e.printStackTrace();            logger.info("文件上传失败!上传文件为:" + oldFilePath);            logger.error("报错信息toString:" + e.toString());        }    }

服务器这里我是用我自己本地的tomcat做的测试服务器,这个你们可以通过配置文件或者自己指定服务器。
下面是服务器端接收文件代码:

@RequestMapping(value = "/uploadFile")    public void uploadFile(HttpServletRequest request, HttpServletResponse response)              throws IOException      {          InputStream is = request.getInputStream();        DataInputStream dis = new DataInputStream(is);        String result = "";        try {            result = saveFile(dis);        } catch (Exception e) {            e.printStackTrace();            result = "uploaderror";        }        request.getSession().invalidate();        response.setContentType("text/html;charset=UTF-8");        ObjectOutputStream dos = new ObjectOutputStream(                    response.getOutputStream());        dos.writeObject(result);        dos.flush();        dos.close();        dis.close();        is.close();    }/**     * 保存文件     * @param dis     * @return     */    private String saveFile(DataInputStream dis) {        String fileurl = "F:/apache-tomcat-7.0.70/webapps/upload/2017-06-12.log";        File file = new File(fileurl);        if (!file.exists()) {            try {                file.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        }        FileOutputStream fps = null;        try {            fps = new FileOutputStream(file);        } catch (FileNotFoundException e) {            e.printStackTrace();        }        int bufferSize = 1024;        byte[] buffer = new byte[bufferSize];        int length = -1;        try {            while ((length = dis.read(buffer)) != -1) {                fps.write(buffer, 0, length);            }        } catch (IOException e) {            e.printStackTrace();        }        try {            fps.flush();            fps.close();        } catch (IOException e) {            e.printStackTrace();        }        return "success";    }

个人情况总结:我个人出现的情况是,上传的文件没有数据,就是DataOutputStream在服务器端接收的时候,是没内容的,可是我在android端调试的时候,明明是能看到数据,后来找了1天时间,找到了原因。因为我上传的是日志文件,属于纯文本文件,可是最开始我设置http中Content-Type格式的时候,我设置的是multipart/form-data格式,到后面改成text/plain格式才能正常上传(之前的我是在网上直接扒下来的,坑~)。所以这里的格式要根据你实际的文件类型来设置。
这里关于Content-Type格式的问题,我参考了以下博客,更详细的讲解可过去看看:
http://blog.csdn.net/blueheart20/article/details/45174399

常见的媒体格式类型如下:

    text/html : HTML格式    text/plain :纯文本格式         text/xml :  XML格式    image/gif :gif图片格式       image/jpeg :jpg图片格式    image/png:png图片格式

以application开头的媒体格式类型:

   application/xhtml+xml :XHTML格式   application/xml     : XML数据格式   application/atom+xml  :Atom XML聚合格式      application/json    : JSON数据格式   application/pdf       :pdf格式    application/msword  : Word文档格式   application/octet-stream : 二进制流数据(如常见的文件下载)   application/x-www-form-urlencoded : 
中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

另外一种常见的媒体格式是上传文件之时使用的:

    multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

以上就是我们在日常的开发中,经常会用到的若干content-type的内容格式。

更多相关文章

  1. Js中JSON.parse函数解析导致的数据异常
  2. [置顶] Android(安卓)错误信息捕获发送至服务器
  3. android 解码出来的视频frame数据,是如何一步步的传递到显示端的(
  4. 金三银四背后,一个 Android(安卓)程序员从被裁到拿到 Offer 的面
  5. Android使用WCF的服务程序之入门
  6. Android(安卓)数据库文件 db 的备份和重载
  7. Android全局主题样式控制,语言设置、主题颜色、字体大小、字体样
  8. Android照相功能驱动层中HAL的实现(基于OK6410开发板+OV9650摄像
  9. Android(安卓)网星工具箱Beta版

随机推荐

  1. ELK 之 elasticsearch集群安装
  2. 如何记忆 Spring Bean 的生命周期
  3. GoPath模式和GoMoudle模式的相爱相杀
  4. 一次 JVM 进程退出的原因分析
  5. 原来这才是Spring Boot使用AOP的正确姿势
  6. C/C++ 性能优化背后的方法论:TMAM
  7. 3.2 Ansible Playbooks 高级二
  8. java io流(File类)
  9. 3.1 Ansible Playbooks 高级一
  10. k8s 集群部署 flannel 报错 Couldn't fet