本文實例講述了java實現分段讀取文件並通過HTTP上傳的方法。分享給大家供大家參考。具體如下:
1、首先將文件分段,用RandomAccessFile
2、分段後將分出的內容上傳到http
URL url = new URL(actionUrl);HttpURLConnection con = (HttpURLConnection) url.openConnection();/** 允許Input、Output,不使用Cache */con.setDoInput(true);con.setDoOutput(true);con. setUseCaches(false);/** 設定傳送的method=POST */con.setRequestMethod("POST");/** setRequestProperty */con.setRequestProperty("Connection", "Keep-Alive");con.setRequestProperty ("Charset", "UTF-8");con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);/** 設定DataOutputStream */DataOutputStream ds = new DataOutputStream( con.getOutputStream());ds.writeBytes(twoHyphens + boundary + end);ds.writeBytes("Content-Disposition: form-data; " + "name=/"file1/";filename=/"" + newName + "/"" + end);ds.writeBytes(end);/** 取得文件的FileInputStream */FileInputStream fStream = new FileInputStream(uploadFile);/** 設定每次寫入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.writeBytes(end);ds.writeBytes(twoHyphens + boundary + twoHyphens + end);/** close streams */fStream. close();ds.flush();
希望本文所述對大家的java程序設計有所幫助。