我知道如何从android上传文件,我可以使用以下代码
来完成private void doFileUpload(MessageModel model) {
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;// 1 MB
String responseFromServer = "";
String imageName = null;
try {
// ------------------ CLIENT REQUEST
File file = new File(model.getMessage());
FileInputStream fileInputStream = new FileInputStream(file);
AppLog.Log(TAG, "File Name :: " + file.getName());
String[] temp = file.getName().split("\\.");
AppLog.Log(TAG, "temp array ::" + temp);
String extension = temp[temp.length - 1];
imageName = model.getUserID() + "_" + System.currentTimeMillis()
+ "." + extension;
// open a URL connection to the Servlet
URL url = new URL(Urls.UPLOAD_VIDEO);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ imageName + "\"" + lineEnd);
Log.i(TAG, "Uploading starts");
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
// Log.i(TAG, "Uploading");
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
AppLog.Log(TAG, "Uploading Vedio :: " + imageName);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug", "File is written");
Log.i(TAG, "Uploading ends");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Debug", "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
// ------------------ read the SERVER RESPONSE ----------------
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
try {
final JSONObject jsonObject = new JSONObject(str);
if (jsonObject.getBoolean("success")) {
handler.post(new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
} else {
handler.post(new Runnable() {
@Override
public void run() {
try {
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
model.setMessage(imageName);
onUploadComplete(model);
inStream.close();
} catch (IOException ioex) {
ioex.printStackTrace();
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
manageQueue();
}
代码适用于短视频但不上传大文件,我没有暗示原因。:(
我知道这是一个不好的做法,只是问我的代码为什么不起作用,但在这里我问为什么代码对大文件的行为不同。
我还检查了StackOverFlow上的其他答案,但在我的代码中没有发现任何缺陷。
由于
答案 0 :(得分:2)
您可以尝试HttpClient jar下载最新的HttpClient jar,将其添加到您的项目中,然后使用以下方法上传视频:
private void uploadVideo(String videoPath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
FileBody filebodyVideo = new FileBody(new File(videoPath));
StringBody title = new StringBody("Filename: " + videoPath);
StringBody description = new StringBody("This is a video of the agent");
StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("videoFile", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
reqEntity.addPart("code", code);
httppost.setEntity(reqEntity);
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown( );
} // end of uploadVideo( )
答案 1 :(得分:1)
试试Android Asynchronous Http Client库。
AsyncHttpClient client = new AsyncHttpClient();
File myFile = new File("/path/to/video");
RequestParams params = new RequestParams();
try {
params.put("video", myFile);
} catch(FileNotFoundException e) {}
client.post("POST URL",params, new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
答案 2 :(得分:1)
尝试使用volley,在项目中添加库并享受,快速且易于集成。
final AbstractUploadServiceReceiver uploadReceiver = new AbstractUploadServiceReceiver() {
@Override
public void onProgress(String uploadId, int progress) {
Log.i("", "upload with ID " + uploadId + " is: " + progress);
}
@Override
public void onError(String uploadId, Exception exception) {
String message = "Error in upload with ID: " + uploadId + ". " + exception.getLocalizedMessage();
Log.e("", message, exception);
}
@Override
public void onCompleted(String uploadId, int serverResponseCode, String serverResponseMessage) {
String message = "Upload with ID " + uploadId + " is completed: " + serverResponseCode + ", "
+ serverResponseMessage;
Log.i("", message);
}
};
uploadReceiver.register(context);
final docUploadParams item="yourdocUploadParam";
sendUploaderRequest(context, URLtoUpload, item);
public void sendUploaderRequest(Context context,String url,docUploadParams item)
{
final UploadRequest request = new UploadRequest(context,url);
//in case of image
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile( ).getName() , ContentType.IMAGE_JPEG);
//in case of audio
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.AUDIO_M3U);
//in case of video
request.addFileToUpload(item.getFile().getAbsolutePath(),"file",item.getFile().getName() , ContentType.VIDEO_MPEG);
//custom parameters if any
request.addParameter("userId",item.userID);
//progress on notification bar
request.setNotificationConfig(R.drawable.ic_launcher,
"Uploading Files",
"Upload in Progress",
"Upload Completed Successfully",
"Error in Uploading",
false);
try {
UploadService.startUpload(request);
} catch (Exception exc) {
exc.printStackTrace();
}
}