1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > android上传文件至服务器(android端+服务器端)

android上传文件至服务器(android端+服务器端)

时间:2020-07-16 13:01:58

相关推荐

android上传文件至服务器(android端+服务器端)

引言:本来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,不使用Cachecon.setDoInput(true);con.setDoOutput(true);con.setUseCaches(false);con.setConnectTimeout(50000);con.setReadTimeout(50000);// 设置传送的method=POSTcon.setRequestMethod("POST");//在一次TCP连接中可以持续发送多份数据而不会断开连接con.setRequestProperty("Connection", "Keep-Alive");//设置编码con.setRequestProperty("Charset", "UTF-8");//text/plain能上传纯文本文件的编码格式con.setRequestProperty("Content-Type", "text/plain");// 设置DataOutputStreamDataOutputStream ds = new DataOutputStream(con.getOutputStream());// 取得文件的FileInputStreamFileInputStream fStream = new FileInputStream(oldFilePath);// 设置每次写入1024bytesint 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/-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格式的问题,我参考了以下博客,更详细的讲解可过去看看:

/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 : <form encType=””>中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

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

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。