Android_文件上传与断点续传
安卓端
数据库帮助类
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { public DBOpenHelper(Context context) { super(context, "upload.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table uploadlog (_id integer primary key autoincrement,uploadfilepath varchar(123),sourceid varchar(10))"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("drop table if exists uploadlog"); onCreate(db); } }
上传日志记录
import java.io.File; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class UploadLogService { private DBOpenHelper dbOpenHelper; public UploadLogService(Context context) { this.dbOpenHelper = new DBOpenHelper(context); } 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() }); } public String getBindId(File uploadFile) { SQLiteDatabase db = dbOpenHelper.getWritableDatabase(); Cursor cursor = db.rawQuery( "select sourceid from uploadlog where uploadfilepath=?", new String[] { uploadFile.getAbsolutePath() }); if(cursor.moveToFirst()) { return cursor.getString(0); } cursor.close(); return null; } }
上传文件类
import java.io.File; import java.io.OutputStream; import java.io.PushbackInputStream; import java.io.RandomAccessFile; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.alin.service.UploadLogService; import com.alin.util.StreamTool; public class UploadActivity extends Activity { private EditText filenameText; private ProgressBar progressBar; private TextView percentView; private UploadLogService logService; private Handler handler = new Handler() { public void handleMessage(Message msg) { int progress = msg.getData().getInt("size"); progressBar.setProgress(progress); double temp = (double) progressBar.getProgress() / (double) progressBar.getMax(); int percent = (int) (temp * 100); Log.i("percent", percent + ""); percentView.setText(percent + "%"); if (progressBar.getProgress() == progressBar.getMax()) { Toast.makeText(UploadActivity.this, R.string.success, Toast.LENGTH_LONG).show(); } }; }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); logService = new UploadLogService(this); filenameText = (EditText) this.findViewById(R.id.filename); progressBar = (ProgressBar) this.findViewById(R.id.uploadbar); percentView = (TextView) this.findViewById(R.id.percent); Button button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new 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.filenotexist, Toast.LENGTH_LONG) .show(); } } else { Toast.makeText(UploadActivity.this, R.string.sdcarderror, Toast.LENGTH_LONG).show(); } } }); } /** * 上传文件 * * @param uploadfile */ private void uploadFile(final File uploadfile) { new Thread(new Runnable() { @Override public void run() { try { progressBar.setMax((int) uploadfile.length()); String sourceid = logService.getBindId(uploadfile); String head = "Content-Length=" + uploadfile.length() + ";filename=" + uploadfile.getName() + ";sourceid=" + (sourceid == null ? "" : sourceid) + "\r\n"; Socket socket = new Socket("10.0.2.2", 7878); OutputStream outStream = socket.getOutputStream(); outStream.write(head.getBytes()); // 服务端返回sourceid=xxx;position=xxx 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 (sourceid == 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 message = new Message(); message.getData().putInt("size", length); handler.sendMessage(message); } fileOutStream.close(); outStream.close(); inStream.close(); socket.close(); if (length == uploadfile.length()) { logService.delete(uploadfile); } } catch (Exception e) { Log.e("error", e.toString()); // e.printStackTrace(); } } }).start(); } }
安卓布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/filename" /> <EditText android:id="@+id/filename" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="YoudaoDict.exe" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button" /> <ProgressBar android:id="@+id/uploadbar" android:layout_width="fill_parent" android:layout_height="20px" style="?android:attr/progressBarStyleHorizontal" /> <TextView android:id="@+id/percent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" /> </LinearLayout>
流工具类
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; public class StreamTool { public static void save(File file, byte[] data) throws Exception { FileOutputStream outStream = new FileOutputStream(file); outStream.write(data); outStream.close(); } 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); } /** * 读取流 * * @param inStream * @return 字节数组 * @throws Exception */ public static byte[] readStream(InputStream inStream) throws Exception { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } }
服务端
文件服务
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PushbackInputStream; import java.io.RandomAccessFile; import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import cn.alin.utils.StreamTool; 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; } } }
启动服务的界面
import java.awt.BorderLayout; import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; 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); } }
客户端测试
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.PushbackInputStream; import java.io.RandomAccessFile; import java.net.Socket; import cn.itcast.alin.StreamTool; public class SocketClient { /** * @param args */ public static void main(String[] args) { try { // Socket socket = new Socket("127.0.0.1", 7878); Socket socket = new Socket("127.0.0.1", 7878); OutputStream outStream = socket.getOutputStream(); String filename = "QQWubiSetup.exe"; File file = new File(filename); String head = "Content-Length="+ file.length() + ";filename="+ filename + ";sourceid=1278916111468\r\n"; outStream.write(head.getBytes()); PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream()); String response = StreamTool.readLine(inStream); System.out.println(response); String[] items = response.split(";"); String position = items[1].substring(items[1].indexOf("=")+1); RandomAccessFile fileOutStream = new RandomAccessFile(file, "r"); fileOutStream.seek(Integer.valueOf(position)); byte[] buffer = new byte[1024]; int len = -1; int i = 0; while( (len = fileOutStream.read(buffer)) != -1){ outStream.write(buffer, 0, len); i++; //if(i==10) break; } fileOutStream.close(); outStream.close(); inStream.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 读取流 * @param inStream * @return 字节数组 * @throws Exception */ public static byte[] readStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while( (len=inStream.read(buffer)) != -1){ outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); } }
***万事万物都有裂痕,那是光照进来的地方***


浙公网安备 33010602011771号