public class UploadService {
public void uploadFile(String filePath,OnUploadProgressListener progress){
File uploadFile=newFile(filePath);
if(uploadFile==null||uploadFile.length()<=0){
progress.onError("文件为空!");
return;
}
long fileSize=uploadFile.length();
String uploadUrl = "http://192.168.0.106:8080/upload_file_service/upload.jsp";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try{
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setChunkedStreamingMode(1024*50);//分块传输
//httpURLConnection.setFixedLengthStreamingMode((int)fileSize);//采用流式的输出
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
DataOutputStream dos = newDataOutputStream(httpURLConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition:form-data; name=\"file\"; filename=\""
+ filePath.substring(filePath.lastIndexOf("/")+ 1)+ "\""+ end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(filePath);
byte[] buffer = new byte[1024]; // 8k
int count = 0;
int currentUploadSize =0;
while ((count = fis.read(buffer)) != -1){
dos.write(buffer, 0, count);
currentUploadSize+=count;
progress.onUploadProgress(fileSize, currentUploadSize);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
dos.close();
is.close();
progress.onComplete(result);
} catch (Exception e){
e.printStackTrace();
}
}
public interface OnUploadProgressListener {
void onUploadProgress(longfileSize,long progress);
void onComplete(String msg);
void onError(String msg);
}
}