我正在同时使用Android应用程序(Java)和相应的后端(Python / Django)。在应用程序中,我记录了一个MP4文件并将其保存到外部存储中。然后,我将MP4文件上传到服务器,但是目前这在Django中破坏了我的settings.DATA_UPLOAD_MAX_MEMORY_SIZE
。我总是可以增加该限制,但是将文件分成多个块似乎是一个不错的选择。
我可以将视频文件拆分为多个块,然后从Android中分段上传吗?我将如何在Python端重新组合这些文件以形成一个视频文件?
现在这是一个漂亮的原始单文件上传,但这是我开始的地方!这是我用来上传文件的Android代码:
private void sendVideoFile(String filename) {
Log.d(TAG, "Sending video from: " + filename);
File file = new File(filename);
int size = (int) file.length();
Log.d(TAG, "Video size: " + size);
final byte[] video_bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(video_bytes, 0, video_bytes.length);
buf.close();
String url ="http://my-server.herokuapp.com/upload_video";
Request stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
Log.d(TAG, response);
} catch (JSONException e) {
e.printStackTrace();
} finally {
isProcessing = false;
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(
VideoFragment.this.getContext(), error.toString(), Toast.LENGTH_LONG).show();
isProcessing = false;
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "video/mp4");
if (mVideoID != null) {
params.put("Video-ID", mVideoID);
}
return params;
}
@Override
public byte[] getBody() throws AuthFailureError {
return video_bytes;
}
};
Log.d(TAG, "Uploading video...");
stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mRequestQueue.add(stringRequest);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
请注意,我使用Volley进行上传,但是如果有更合适的库可以切换库。
和Python:
def upload_video(request):
if request.method == "POST":
logger.info("Loading session: {}".format(request.META['HTTP_VIDEO_ID']))
video = Video.objects.filter(slug=request.META['HTTP_VIDEO_ID']).first()
video_bytes = io.BytesIO(request.body)
video_name = "{}/video_{}.mp4".format(video.slug, datetime.now())
video.video.save(video_name, File(video_bytes), save=True)
logger.info("Saved video: {}".format(video_name))
return JsonResponse({'video_id': request.META.get('HTTP_VIDEO_ID')})
任何答案或朝正确方向推都将有帮助!谢谢!