日期:2014-05-17 浏览次数:20915 次
/**
*Description: encapsule http protocol of uploading.
*@param url The server url of handleing upload.
*@param sessionId Session id
*@param uploadFile The file that is going to be uploaded
*@param param Other form parameters
*@return
*@throws
*/
public static void doMultipartUpload( String url, String sessionId,
File uploadFile, Map<String, String> param,
UploadApplet applet, List<Map<String, String>> fileList,
int index) {
long blockSize = 5*MB;
int rate = 0;
long fileSize = uploadFile.length();
long uploadCount = ((long)(fileSize - 1)/blockSize) + 1;
System.out.println("before loop ..................."+fileSize+"....."+ uploadCount);
param.put("mu", "1");
List<Map<String, String>> fList = fileList;
Map<String, String> fm = (Map)fList.get(index);
for(long i = 0 ; i < uploadCount; i++) {
param.put("n", "" + i);
doMultipartUploadOne(url,i,blockSize, sessionId, uploadFile,param);
rate = (int)((float)i / (float)uploadCount * 100);
fm.put("RATE", ""+rate);
updateUploadInfo(applet, fList);
}
fm.put("RATE", "100");
updateUploadInfo(applet, fList);
}
/**
*
*/
public static void doMultipartUploadOne(String url,long n, long blockSize, String sessionId, File uploadFile, Map param) {
try {
long skip = n * blockSize;
RandomAccessFile fin = new RandomAccessFile(uploadFile, "r");
fin.seek(skip);
long fileSize = fin.length();
long uploadSize = (skip + blockSize > fileSize) ? fileSize - skip : blockSize;
URL u = new URL(url);
byte[] form_part = getFormData(param);
byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();
long size = form_part.length + uploadSize + end_data.length;
HttpURLConnection con = (HttpURLConnection)u.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.addRequestProperty("Cookie","JSESSIONID="+sessionId);
con.addRequestProperty("Connection","Keep-Alive");
con.addRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type","multipart/form-data; boundary="+boundary);
con.setRequestProperty("Content-Length",String.valueOf(size));
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.write(form_part);
StringBuffer headerBuf = new StringBuffer();
headerBuf.append("Content-Disposition: form-data; name=\"file\"; filename=\"")
.append(uploadFile.getAbsolutePath()).append("\"\r\n");
headerBuf.append("Content-Type: application/octet-stream\r\n\r\n");
out.write(headerBuf.toString().getBytes());
int rn2 = 0;
long loadLen = 0L;
byte[] buf2 = new byte[1024];
while((rn2=fin.read(buf2, 0, 1024))>0)
{
if(loadLen + rn2 >= blockSize){
out.write(buf2,0,