Android大文件断点上传
2013-10-09 15:57
176 查看
源代码下载处:
http://download.csdn.net/user/zl594389970
在Android中除了通过http协议上传小文件外,还可以通过Socket上传较大的文件
案例具体思路:
文件被第一次上传时发送: "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+null+"\r\n";字段给服务器
服务器收到字段后,看到文件的sourceid字段值为空,则表示该文件第一次上传,服务器就会自动为其创建id,并且在本地根据文件名建立相应文件用于接收文件数据,同时把该文件路径和id保存在Map集合中,并发送:“sourceid="+ id+ ";position=0\r\n";内容给客户端,客户端收到服务器为其创建的id和应该从上传文件的什么位置开始读取信息后,在SQLite数据库中记录下本次上传文件的id和文件路径,然后上传文件。
服务器端则开始接收从客户端发来的数据并保存起来,并且时刻把该文件的上传的数据大小保存在以该文件命名的.log文件中。
当在发送的的时候突然关机或网络出现状况,当再次上传该文件时,客户端就会从SQLite中根据文件路径查找到已上传文件的id,然后发送内容给服务器端,服务器从发来的sourceid字段中读到了数据,就从map集合中找到该文件路径,然后根据路径和文件名找到.log文件,并从中读取上次上传文件的大小发送给客户端,客户端得到后遍选择从文件的指定文件读取上传,服务器则再次接收并从文件指定位置保存。
服务器端代码:
界面代码:
主要类FileServer的代码
工具类StreamTool代码
Android客户端的界面:
Android客户端主要负责上传的代码:
按钮点击后调用uploadFile方法上传文件
uploadFile方法:
UploadLogService的主要方法
http://download.csdn.net/user/zl594389970
在Android中除了通过http协议上传小文件外,还可以通过Socket上传较大的文件
案例具体思路:
文件被第一次上传时发送: "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+null+"\r\n";字段给服务器
服务器收到字段后,看到文件的sourceid字段值为空,则表示该文件第一次上传,服务器就会自动为其创建id,并且在本地根据文件名建立相应文件用于接收文件数据,同时把该文件路径和id保存在Map集合中,并发送:“sourceid="+ id+ ";position=0\r\n";内容给客户端,客户端收到服务器为其创建的id和应该从上传文件的什么位置开始读取信息后,在SQLite数据库中记录下本次上传文件的id和文件路径,然后上传文件。
服务器端则开始接收从客户端发来的数据并保存起来,并且时刻把该文件的上传的数据大小保存在以该文件命名的.log文件中。
当在发送的的时候突然关机或网络出现状况,当再次上传该文件时,客户端就会从SQLite中根据文件路径查找到已上传文件的id,然后发送内容给服务器端,服务器从发来的sourceid字段中读到了数据,就从map集合中找到该文件路径,然后根据路径和文件名找到.log文件,并从中读取上次上传文件的大小发送给客户端,客户端得到后遍选择从文件的指定文件读取上传,服务器则再次接收并从文件指定位置保存。
服务器端代码:
界面代码:
public class ServerWindow extends Frame{ private FileServer s = new FileServer(7878); private Label label; public ServerWindow(String title){ super(title); label = new Label(); add(label, BorderLayout.PAGE_START); label.setText("服务器已经启动"); this.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { new Thread(new Runnable() { @Override public void run() { try { s.start(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { s.quit(); System.exit(0); } @Override public void windowClosed(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } }); } /** * @param args */ public static void main(String[] args) { ServerWindow window = new ServerWindow("文件上传服务端"); window.setSize(300, 300); window.setVisible(true); } }
主要类FileServer的代码
public class FileServer { private ExecutorService executorService;//线程池 private int port;//监听端口 private boolean quit = false;//退出 private ServerSocket server; private Map<Long, FileLog> datas = new HashMap<Long, FileLog>();//存放断点数据 public FileServer(int port){ this.port = port; //创建线程池,池中具有(cpu个数*50)条线程 executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50); } /** * 退出 */ public void quit(){ this.quit = true; try { server.close(); } catch (IOException e) { } } /** * 启动服务 * @throws Exception */ public void start() throws Exception{ server = new ServerSocket(port); while(!quit){ try { Socket socket = server.accept(); //为支持多用户并发访问,采用线程池管理每一个用户的连接请求 executorService.execute(new SocketTask(socket)); } catch (Exception e) { e.printStackTrace(); } } } private final class SocketTask implements Runnable{ private Socket socket = null; public SocketTask(Socket socket) { this.socket = socket; } @Override public void run() { try { System.out.println("accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort()); PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream()); //得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid= //如果用户初次上传文件,sourceid的值为空。 String head = StreamTool.readLine(inStream); System.out.println(head); if(head!=null){ //下面从协议数据中提取各项参数值 String[] items = head.split(";"); String filelength = items[0].substring(items[0].indexOf("=")+1); String filename = items[1].substring(items[1].indexOf("=")+1); String sourceid = items[2].substring(items[2].indexOf("=")+1); long id = System.currentTimeMillis();//生产资源id,如果需要唯一性,可以采用UUID FileLog log = null; if(sourceid!=null && !"".equals(sourceid)){ id = Long.valueOf(sourceid); log = find(id);//查找上传的文件是否存在上传记录 } File file = null; int position = 0; if(log==null){//如果上传的文件不存在上传记录,为文件添加跟踪记录 String path = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date()); File dir = new File("file/"+ path); if(!dir.exists()) dir.mkdirs(); file = new File(dir, filename); if(file.exists()){//如果上传的文件发生重名,然后进行改名 filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf(".")); file = new File(dir, filename); } save(id, file); }else{// 如果上传的文件存在上传记录,读取上次的断点位置 file = new File(log.getPath());//从上传记录中得到文件的路径 if(file.exists()){ File logFile = new File(file.getParentFile(), file.getName()+".log"); if(logFile.exists()){ Properties properties = new Properties(); properties.load(new FileInputStream(logFile)); position = Integer.valueOf(properties.getProperty("length"));//读取断点位置 } } } OutputStream outStream = socket.getOutputStream(); String response = "sourceid="+ id+ ";position="+ position+ "\r\n"; //服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=0 //sourceid由服务生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传 outStream.write(response.getBytes()); RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd"); if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));//设置文件长度 fileOutStream.seek(position);//移动文件指定的位置开始写入数据 byte[] buffer = new byte[1024]; int len = -1; int length = position; while( (len=inStream.read(buffer)) != -1){//从输入流中读取数据写入到文件中 fileOutStream.write(buffer, 0, len); length += len; Properties properties = new Properties(); properties.put("length", String.valueOf(length)); FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log")); properties.store(logFile, null);//实时记录文件的最后保存位置 logFile.close(); } if(length==fileOutStream.length()) delete(id); fileOutStream.close(); inStream.close(); outStream.close(); file = null; } } catch (Exception e) { e.printStackTrace(); }finally{ try { if(socket!=null && !socket.isClosed()) socket.close(); } catch (IOException e) {} } } } public FileLog find(Long sourceid){ return datas.get(sourceid); } //保存上传记录 public void save(Long id, File saveFile){ //日后可以改成通过数据库存放 datas.put(id, new FileLog(id, saveFile.getAbsolutePath())); } //当文件上传完毕,删除记录 public void delete(long sourceid){ if(datas.containsKey(sourceid)) datas.remove(sourceid); } private class FileLog{ private Long id; private String path; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public FileLog(Long id, String path) { this.id = id; this.path = path; } } }
工具类StreamTool代码
public class StreamTool {
// 读取从客户端发来的 "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+(souceid==null? "" : souceid)+"\r\n";
// 读到回车换行前面的内容 public static String readLine(PushbackInputStream in) throws IOException { char buf[] = new char[128]; int room = buf.length; int offset = 0; int c; loop: while (true) { switch (c = in.read()) { case -1: case '\n': break loop; case '\r': int c2 = in.read(); if ((c2 != '\n') && (c2 != -1)) in.unread(c2); break loop; default: if (--room < 0) { char[] lineBuffer = buf; buf = new char[offset + 128]; room = buf.length - offset - 1; System.arraycopy(lineBuffer, 0, buf, 0, offset); } buf[offset++] = (char) c; break; } } if ((c == -1) && (offset == 0)) return null; return String.copyValueOf(buf, 0, offset); } }
Android客户端的界面:
Android客户端主要负责上传的代码:
按钮点击后调用uploadFile方法上传文件
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String filename = filenameText.getText().toString(); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File uploadFile = new File(Environment.getExternalStorageDirectory(), filename); if(uploadFile.exists()){ uploadFile(uploadFile); }else{ Toast.makeText(UploadActivity.this, R.string.filenotexsit, 1).show(); } }else{ Toast.makeText(UploadActivity.this, R.string.sdcarderror, 1).show(); } } });
uploadFile方法:
private void uploadFile(final File uploadFile) { new Thread(new Runnable() { @Override public void run() { try { uploadbar.setMax((int)uploadFile.length()); // 设置进度条 String souceid = logService.getBindId(uploadFile); //调用logService获取文件的id,第一次上传没有记录会得到null String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+ (souceid==null? "" : souceid)+"\r\n"; Socket socket = new Socket("172.19.68.65", 7878); // 建立socket连接 OutputStream outStream = socket.getOutputStream(); outStream.write(head.getBytes()); PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream()); String response = StreamTool.readLine(inStream); String[] items = response.split(";"); String responseid = items[0].substring(items[0].indexOf("=")+1); String position = items[1].substring(items[1].indexOf("=")+1); if(souceid==null){//代表原来没有上传过此文件,往数据库添加一条绑定记录 logService.save(responseid, uploadFile); } RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r"); fileOutStream.seek(Integer.valueOf(position)); // 设置文件读取的位置 byte[] buffer = new byte[1024]; int len = -1; int length = Integer.valueOf(position); while( (len = fileOutStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); length += len; Message msg = new Message(); msg.getData().putInt("size", length); handler.sendMessage(msg); } fileOutStream.close(); outStream.close(); inStream.close(); socket.close(); if(length==uploadFile.length()) logService.delete(uploadFile); } catch (Exception e) { e.printStackTrace(); } } }).start(); }
UploadLogService的主要方法
public class UploadLogService { private DBOpenHelper dbOpenHelper; public UploadLogService(Context context){ this.dbOpenHelper = new DBOpenHelper(context); } // 保存文件的id和文件路径 public void save(String sourceid, File uploadFile){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("insert into uploadlog(uploadfilepath, sourceid) values(?,?)", new Object[]{uploadFile.getAbsolutePath(),sourceid}); } // 删除该文件记录 public void delete(File uploadFile){ SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); db.execSQL("delete from uploadlog where uploadfilepath=?", new Object[]{uploadFile.getAbsolutePath()}); } // 根据文件路径获取文件id public String getBindId(File uploadFile){ SQLiteDatabase db = dbOpenHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select sourceid from uploadlog where uploadfilepath=?", new String[]{uploadFile.getAbsolutePath()}); if(cursor.moveToFirst()){ return cursor.getString(0); } return null; } }
相关文章推荐
- android网络编程之HttpUrlConnection的讲解--实现文件的断点上传
- Android应用开发之使用Socket进行大文件断点上传续传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android 文件断点上传器[多用户并发访问]
- Android应用开发之使用Socket进行大文件断点上传续传
- Android应用开发之使用Socket进行大文件断点上传续传
- Android FTP 断点上传文件
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android--第四天(网络图片查看器,多线程下载,文件断点上传原理,Intent,Activity生命周期,广播,服务)
- Android文件断点上传器[多用户并发访问]
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传
- Android中Socket大文件断点上传