




已阅读5页,还剩8页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
android之网络文件上传下载源码效果图:Main.xml: AndroidManifest.xml: 加上 FromFile.javapackage ;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;public class FormFile private bytedata;private InputStream inStream;private File file;private String filename;private String parameterName;private String contentType = application/octet-stream;public FormFile(String filename, byte data, String parameterName, String contentType) this.data = data;this.filename = filename;this.parameterName = parameterName;if(contentType!=null)this.contentType = contentType;public FormFile(String filename,File file,String parameterName,String contentType)this.filename = filename;this.parameterName = parameterName;this.file = file;trythis.inStream = new FileInputStream(file);catch(FileNotFoundException e)e.printStackTrace();if(contentType != null)this.contentType = contentType;public File getFile()return file;public InputStream getInStream()return inStream;public byte getData()return data;public String getFilename()return filename;public void setFilename(String filename)this.filename = filename;public String getParameterName()return parameterName;public void setParameterName(String parameterName)this.parameterName = parameterName;public String getContentType()return contentType;public void setContentType(String contentType)this.contentType = contentType;FileUtils.java:package ;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.os.Environment;public class FileUtils private String SDPATH;public String getSDPATH()return SDPATH;public void setSDPATH(String sDPATH)SDPATH = sDPATH;/获取SD卡目录public FileUtils()SDPATH = Environment.getExternalStorageDirectory() + /;System.out.println(sd cards directory path is : + SDPATH);/在SD卡上创建文件public File createSDFile(String fileName)throws IOExceptionFile file = new File(SDPATH + fileName);file.createNewFile();return file;/在SD卡上创建目录public File createSDDir(String dirName)File dir = new File(SDPATH + dirName);System.out.println(storge devices state : +Environment.getExternalStorageState();if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)System.out.println(this directory real path is:+dir.getAbsolutePath();System.out.println(the result of making directory:+dir.mkdir();return dir;/判断SD卡的文件夹是否存在public boolean isFileExist(String fileName)File file = new File(SDPATH + fileName);return file.exists();/将一个inputStream里面的数据写入到SD卡中public File write2SDFromInput(String path,String fileName,InputStream inputStream)File file = null;OutputStream output = null;tryFile tempf = createSDDir(path);System.out.println(directory in the sd card: + tempf.exists();file = createSDFile(path + fileName);output = new FileOutputStream(file);byte buffer = new byte4*1024;int length = 0;while(length = inputStream.read(buffer) != -1)output.write(buffer, 0, length);System.out.println(length);output.flush();catch(FileNotFoundException e)e.printStackTrace();catch(IOException e)e.printStackTrace();finallytryoutput.close();catch(IOException e)e.printStackTrace();return file;HttpDownloader.java:package ;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .HttpURLConnection;import .MalformedURLException;import .URL;public class HttpDownloader private URL url = null;/* * 下载步骤: * 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 * 3.得到InputStream * 4.从InputStream当中读取数据 */public String download(String urlStr)StringBuffer sb = new StringBuffer();String line = null;BufferedReader buffer = null;tryurl = new URL(urlStr);HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream();while(line = buffer.readLine() != null)sb.append(line);catch(Exception e)e.printStackTrace();finallytrybuffer.close();catch(IOException e)e.printStackTrace();return sb.toString();public int downFile(String urlStr, String path, String fileName)InputStream inputStream = null;tryFileUtils fileUtils = new FileUtils();if(fileUtils.isFileExist(path + fileName)return 1;elseinputStream = getInputStreamFromURL(urlStr);File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);if(resultFile = null)return -1;catch(Exception e)e.printStackTrace();return -1;finallytryinputStream.close();catch(IOException e)e.printStackTrace();return 0;public InputStream getInputStreamFromURL(String urlStr)HttpURLConnection urlConn = null;InputStream inputStream = null;tryurl = new URL(urlStr);urlConn = (HttpURLConnection)url.openConnection();inputStream = urlConn.getInputStream();catch(MalformedURLException e)e.printStackTrace();catch(IOException e)e.printStackTrace();return inputStream;HttpUploader.java:package ;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import .InetAddress;import .Socket;import .URL;import java.util.Map;public class HttpUploader public static boolean post(String path, Map params, FormFile files)throws Exceptionfinal String BOUNDARY = -7da2137580612;final String endline = BOUNDARY + -rn;int fileDataLength = 0;for(FormFile uploadFile : files)StringBuilder fileExplain = new StringBuilder();fileExplain.append(-);fileExplain.append(BOUNDARY);fileExplain.append(rn);fileExplain.append(Content-Disposition:form-data;name=+ uploadFile.getParameterName()+;filename=+ uploadFile.getFilename() + rn);fileExplain.append(Content-Type: + uploadFile.getContentType()+rnrn);fileExplain.append(rn);fileDataLength += fileExplain.length();if(uploadFile.getInStream()!=null)fileDataLength += uploadFile.getFile().length();elsefileDataLength += uploadFile.getData().length;/*StringBuilder textEntity = new StringBuilder();for(Map.Entry entry : params.entrySet()textEntity.append(-);textEntity.append(BOUNDARY);textEntity.append(rn);textEntity.append(Content-Disposition: form-data; name=+ entry.getKey() + rnrn);textEntity.append(entry.getValue();textEntity.append(rn);int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length; */URL url = new URL(path);int port = url.getPort() = -1 ? 80 : url.getPort();Socket socket = new Socket(InetAddress.getByName(url.getHost(), port); OutputStream outStream = socket.getOutputStream();String requestmethod = POST + url.getPath()+ HTTP/1.1rn; outStream.write(requestmethod.getBytes();String accept = Accept:image/gif,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/xaml+xml,application/vnd.ms-xpdocument,application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*rn;outStream.write(accept.getBytes();String language = Accept-Language: zh-CNrn;outStream.write(language.getBytes();String contenttype = Content-Type: multipart/form-data; boundary=+ BOUNDARY+ rn;outStream.write(contenttype.getBytes();String contentlength = Content-Length: + fileDataLength + rn;/String contentlength = Content-Length: + dataLength + rn;outStream.write(contentlength.getBytes();String alive = Connection: Keep-Alivern;outStream.write(alive.getBytes();String host = Host: + url.getHost() +:+ port +rn;outStream.write(host.getBytes();/写完HTTP请求头后根据HTTP协议再写一个回车换行 outStream.write(rn.getBytes(); /把所有文本类型的实体数据发送出来 / outStream.write(textEntity.toString().getBytes(); /把所有文件类型的实体数据发送出来 for(FormFile uploadFile : files) StringBuilder fileEntity = new StringBuilder(); fileEntity.append(-); fileEntity.append(BOUNDARY); fileEntity.append(rn); fileEntity.append(Content-Disposition: form-data;name=+ uploadFile.getParameterName()+;filename=+ uploadFile.getFilename() + rn); fileEntity.append(Content-Type: + uploadFile.getContentType()+rnrn); outStream.write(fileEntity.toString().getBytes(); if(uploadFile.getInStream()!=null) byte buffer = new byte1024; int len = 0; while(len = uploadFile.getInStream().read(buffer, 0, 1024)!=-1) outStream.write(buffer, 0, len); uploadFile.getInStream().close(); else outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); outStream.write(rn.getBytes(); outStream.write(rn.getBytes(); /下面发送数据结束标志,表示数据已经结束 outStream.write(endline.getBytes(); /* BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(); if(reader.readLine().indexOf(200)=-1) /读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败 return false; */ outStream.flush(); outStream.close(); / reader.close(); socket.close(); return true; /* * 提交数据到服务器 * * param path 上传路径(注:避免使用localhost或这样的路径测试,因为它会指向手机模拟器,你可以使用或0:8080这样的路径测试) * * param params 请求参数 key为参数名,value为参数值 * * param file 上传文件 */ public static boolean post(String path, Map params, FormFile file) throws Exceptionreturn post(path, params, new FormFilefile);HttpclientActivity.java:package ;import java.io.File;import java.util.HashMap;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class HttpclientActivity extends Activity private EditText downloadText;private Button downloadButton;private EditText uploadfileText;private Button uploadButton;private File file;private Handler handler;private static final String TAG=MainActivity; /* Called when the activity is first created. */ Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadText = (EditText)findViewById(R.id.downloadfile); downloadButton = (Button)findViewById(R.id.download); downloadButton.setOnClickListener(new DownloadListener(); uploadfileText = (EditText)findViewById(R.id.uploadfile); uploadButton = (Button)findViewById(R.id.upload); uploadButton.setOnClickLi
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025贵州黄平县中医医院医共体单位纸房乡卫生院招聘2名护理人员模拟试卷参考答案详解
- 2025湖南株洲市工业中等专业学校招聘第一批高层次人才13人模拟试卷及答案详解参考
- 2025湖北神农架优抚医院招聘医疗卫生专业技术人员模拟试卷附答案详解(模拟题)
- 2025江苏徐州选聘徐州泉山经济开发区投资发展有限公司总经理(四)考前自测高频考点模拟试题附答案详解
- 2025安徽蚌埠市教育局局属中学高层次人才招聘50人模拟试卷附答案详解(突破训练)
- 2025年上半年浙江宏为电力建设有限公司社招(若干人)笔试题库历年考点版附带答案详解
- 2025河南驻马店市正阳县县管国有企业招聘20人(第二批)考前自测高频考点模拟试题及答案详解(必刷)
- 2025广东海洋大学招聘辅导员32人模拟试卷完整答案详解
- 2025内蒙古赤峰新正电工技术服务有限公司面向社会招聘69人模拟试卷附答案详解(黄金题型)
- 2025广东依顿电子科技股份有限公司招聘工艺工程师岗人员考前自测高频考点模拟试题参考答案详解
- 乌鲁木齐家乡介绍旅游攻略
- (高清版)JTGT 3365-01-2020 公路斜拉桥设计规范
- 专业技术人员年度考核情况登记表
- GB/T 33285.2-2024皮革和毛皮烷基酚及烷基酚聚氧乙烯醚的测定第2部分:间接法
- 2023年贵州专升本英语真题试卷(完整版)
- 医院护理培训课件:《成人早期预警评分系统介绍》
- 2023保密知识测试题库含答案
- 危险化学品安全作业(氧化工艺)考试题库(含答案)
- 中国农业银行笔试题库(含答案)
- GA 1808-2022军工单位反恐怖防范要求
- 工程建设项目绿色建造施工水平评价申请表
评论
0/150
提交评论