我想上传超过2Mb的视频,但我无法上传。
我试图通过改造上传,但我正在
TimeoutException异常
然后我尝试了多部分请求请求,但我无法上传它。
服务器端没有问题,因为我们可以通过IOS应用程序 上传意味着服务器配置正确的视频。
这是我用来上传视频的代码。
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
JSONObject jsonObjectData = new JSONObject();
jsonObjectData.put("api_key", "2fdaeddaeef77d488a5_5f2e");
jsonObjectData.put("email", "example@gmail.com");
jsonObjectData.put("access_token", "e1507300a57bf999accb593c1f04c9bdbdce5da7a9086160c4497e160da0ff74");
jsonObjectData.put("request_token", "188d25eda1688119f2e133885a75726d2963e5f2eef4f87524b16da248544607");
jsonObjectData.put("request_timestamp", "1459333407");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://admin.eyesoncrime.co.uk/api/v1/videos/upload");
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("data", jsonObjectData.toString());
conn.setRequestProperty("file_name", sourceFile.getName());
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file_upl\";filename=\""
+ fileName + "\"" + lineEnd);
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) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getContentEncoding();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" C:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("server Exception", "Upload file to server Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
更新1:
现在我按照@BNK here的建议尝试了OkHttp,但是获得了套接字超时异常
public class MainActivity extends AppCompatActivity {
private final int REQUEST_TAKE_GALLERY_VIDEO = 101;
private final Context mContext = this;
private static final String LOG_TAG = "OkHttp";
private TextView mTextView;
private Handler mHandler;
private String filemanagerstring= "";
private static final MediaType MEDIA_TYPE_VIDEO = MediaType.parse("video/*");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView);
mHandler = new Handler(Looper.getMainLooper());
}
public void upload(String filemanagerstring){
JSONObject jsonObjectData = new JSONObject();
try {
jsonObjectData.put("api_key", "2fdaeddaeef77d488a5_5f2e");
jsonObjectData.put("email", "neerajrathi81@gmail.com");
jsonObjectData.put("access_token", "e1507300a57bf999accb593c1f04c9bdbdce5da7a9086160c4497e160da0ff74");
jsonObjectData.put("request_token", "188d25eda1688119f2e133885a75726d2963e5f2eef4f87524b16da248544607");
jsonObjectData.put("request_timestamp", "1459333407");
} catch (JSONException e) {
e.printStackTrace();
}
File sourceFile = new File(filemanagerstring);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; file_name=\"" + sourceFile.getName() + "\"" + "\r\n"),
RequestBody.create(null, "Sample Text Content"))
.addPart(
Headers.of("Content-Disposition", "form-data; data=\"" + jsonObjectData.toString() + "\"" + "\r\n"),
RequestBody.create(null, jsonObjectData.toString()))
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"file\"; filename=\"ECO_video.mp4\""),
RequestBody.create(MEDIA_TYPE_VIDEO, sourceFile))
.build();
final Request request = new Request.Builder()
.url("http://admin.eyesoncrime.co.uk/api/v1/videos/upload")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Request request, final IOException e) {
Log.e(LOG_TAG, e.toString());
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
mTextView.setText(e.toString());
}
});
}
@Override
public void onResponse(Response response) throws IOException {
final String message = response.toString();
Log.i(LOG_TAG, message);
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
mTextView.setText(message);
}
});
}
});
}
public void openGallery(View view) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), REQUEST_TAKE_GALLERY_VIDEO);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
Uri selectedImageUri = data.getData();
// MEDIA GALLERY
filemanagerstring = getPath(selectedImageUri);
upload(filemanagerstring);
}
}
}
// UPDATED!
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
请建议任何解决方案。感谢。