Android 使用multipart将多个带有视频的图像逐个上载到服务器
你好堆栈溢出社区 我想发送一个视频多个图像到服务器一个接一个。为了实现这一点,我编写了一个服务,将图像一个接一个地同步上传到服务器。但在这里,我遇到了一个问题,当我向服务器发送20个图像时,只有少数图像得到保存,但所有20个图像的响应都是200。 假设我向服务器发送了20个图像,但只保存了10到12个 我不明白是什么问题,是服务器端问题吗 除了我,还有谁能面对这个问题吗 这是我的服务代码片段Android 使用multipart将多个带有视频的图像逐个上载到服务器,android,android-volley,multipartform-data,Android,Android Volley,Multipartform Data,你好堆栈溢出社区 我想发送一个视频多个图像到服务器一个接一个。为了实现这一点,我编写了一个服务,将图像一个接一个地同步上传到服务器。但在这里,我遇到了一个问题,当我向服务器发送20个图像时,只有少数图像得到保存,但所有20个图像的响应都是200。 假设我向服务器发送了20个图像,但只保存了10到12个 我不明白是什么问题,是服务器端问题吗 除了我,还有谁能面对这个问题吗 这是我的服务代码片段 @Override public void onCreate() { supe
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "Service created");
createNotification();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
networkMonitorReceiver = NetworkMonitorReceiver.getInstance();
networkMonitorReceiver.setNetworkChangeListener(NetworkMonitoringService.this);
registerReceiver(networkMonitorReceiver, intentFilter);
}
/**
* When the app's NetworkConnectionActivity is created, it starts this service. This is so that the
* activity and this service can communicate back and forth. See "setUiCallback()"
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
if (intent != null) {
docLocation = intent.getStringExtra(ConstantsBundleTags.DOC_LOCATION);
pickupUniqueNumber = intent.getStringExtra(ConstantsBundleTags.PICKUP_UNIQUE_NUMBER);
chassisNo = intent.getStringExtra(ConstantsBundleTags.CHASSIS_NO);
}
return START_REDELIVER_INTENT;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
if (networkMonitorReceiver != null) {
Log.e(TAG, "onDestroy: ");
unregisterReceiver(networkMonitorReceiver);
networkMonitorReceiver = null;
}
}
public byte[] getImageFromBitmap(Context context, String imagePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
options.inSampleSize = calculateInSampleSize(options, Math.abs(500), Math.abs(500));
options.inJustDecodeBounds = false;
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeFile(imagePath, options);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
public byte[] convertVideoToByte(Context context, String imagePath) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
FileInputStream inputStream = new FileInputStream(imagePath);
ByteBuffer byteBuffer = ByteBuffer.allocate(inputStream.available());
inputStream.getChannel().read(byteBuffer);
byteArrayOutputStream.write(byteBuffer.array());
} catch (IOException e) {
e.printStackTrace();
}
return byteArrayOutputStream.toByteArray();
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
/* final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}*/
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
@Override
public void onResponse(NetworkResponse response) {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
deleteFiles();
stopSelf();
}
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(this, "onErrorResponse: " + error.getMessage(), Toast.LENGTH_SHORT).show();
Log.e(TAG, "onErrorResponse: " + error.getMessage());
// stopSelf();
}
private void deleteFiles() {
Utility.deleteFolder(NetworkMonitoringService.this, chassisNo);
// Utility.deleteFolder(NetworkMonitoringService.this, chassisNo);
}
private void sendImagesToServer() {
HashMap<String, String> params = new HashMap<>();
byteData = new HashMap<>();
SharedPreferences preferences = getSharedPreferences(Constants.LOGIN_DATA_PREFS, MODE_PRIVATE);
params.put("docLocation", docLocation);
params.put("uniqueNo", pickupUniqueNumber);
params.put("countryCode", Constants.COUNTRY_CODE);
params.put("companyId", preferences.getString(ConstantsSharedPrefs.PREFS_KEY_COMPANY_ID, ""));
params.put("loginUserId", preferences.getString(ConstantsSharedPrefs.PREFS_KEY_USER_ID, ""));
params.put("imageCountByApp", String.valueOf(Utility.getActualFilesCount(this,chassisNo,Constants.MEDIA_TYPE_IMAGES)));
Log.d("request---", params.toString());
File dir = Utility.getRootDirectory(NetworkMonitoringService.this, chassisNo);
listFilesForFolder(dir);
PhotoMultipartRequest<NetworkResponse> multipartRequest = new PhotoMultipartRequest<NetworkResponse>
(
Request.Method.POST,
this.getResources().getString(R.string.api_url_main) + "Workshop/SavePickupImage", params, byteData, NetworkResponse.class,
this, this);
RequestQueue requestQueue = Volley.newRequestQueue(NetworkMonitoringService.this);
requestQueue.add(multipartRequest);
requestQueue.getCache().clear();
}
//todo rb
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
String filename = fileEntry.getAbsolutePath();
if (filename.contains(".mp4")) {
PhotoMultipartRequest.DataPart dataPart = new PhotoMultipartRequest.DataPart(filename,
"video/mp4", convertVideoToByte(NetworkMonitoringService.this, filename));
byteData.put("video" , dataPart);
} else {
PhotoMultipartRequest.DataPart dataPart = new PhotoMultipartRequest.DataPart(filename,
"image/jpg", getImageFromBitmap(NetworkMonitoringService.this, filename));
byteData.put("image" , dataPart);
}
}
}
}
private void createNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("NetworkState", "Network State", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notification = new NotificationCompat.Builder(NetworkMonitoringService.this, "NetworkState")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(getResources().getText(R.string.app_name))
.setContentTitle(getResources().getText(R.string.app_name))
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_HIGH)
.setLights(Color.parseColor("#B71C1C"), 1000, 6000)
.build();
startForeground(NOTIFICATION_ID, notification);
}
@Override
public void OnNetworkChange(boolean isConnect) {
if (isConnect) {
Toast.makeText(NetworkMonitoringService.this, "Connected", Toast.LENGTH_SHORT).show();
startForeground(NOTIFICATION_ID, notification);
sendImagesToServer();
} else {
Toast.makeText(NetworkMonitoringService.this, "Disconnected", Toast.LENGTH_SHORT).show();
stopForeground(true);
}
}
}
@覆盖
public void onCreate(){
super.onCreate();
Log.e(标记“创建的服务”);
createNotification();
IntentFilter IntentFilter=新的IntentFilter(ConnectivityManager.CONNECTIVITY_操作);
networkMonitorReceiver=networkMonitorReceiver.getInstance();
networkMonitorReceiver.setNetworkChangeListener(NetworkMonitoringService.this);
registerReceiver(网络监视器Receiver、intentFilter);
}
/**
*创建应用程序的网络连接活动后,它将启动此服务。这是因为
*活动和此服务可以来回通信。请参阅“setUiCallback()
*/
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
Log.e(标记“onStartCommand”);
if(intent!=null){
docLocation=intent.getStringExtra(ConstantsBundleTags.DOC\u位置);
pickupUniqueNumber=intent.getStringExtra(ConstantsBundleTags.PICKUP\u唯一\u编号);
chassisNo=intent.getStringExtra(ConstantsBundleTags.CHASSIS_编号);
}
返回启动\u重新交付\u意图;
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
@凌驾
公共空间{
super.ondestory();
if(networkMonitorReceiver!=null){
Log.e(标签“onDestroy:”);
未注册接收器(网络监视器接收器);
networkMonitorReceiver=null;
}
}
公共字节[]getImageFromBitmap(上下文上下文,字符串imagePath){
BitmapFactory.Options=new-BitmapFactory.Options();
options.inJustDecodeBounds=true;
解码文件(imagePath,选项);
options.inSampleSize=calculateInSampleSize(选项,Math.abs(500),Math.abs(500));
options.inJustDecodeBounds=false;
位图=空;
位图=BitmapFactory.decodeFile(图像路径,选项);
ByteArrayOutputStream ByteArrayOutputStream=新建ByteArrayOutputStream();
compress(bitmap.CompressFormat.JPEG,80,byteArrayOutputStream);
返回byteArrayOutputStream.toByteArray();
}
公共字节[]convertVideoToByte(上下文上下文,字符串imagePath){
ByteArrayOutputStream ByteArrayOutputStream=新建ByteArrayOutputStream();
试一试{
FileInputStream inputStream=新的FileInputStream(imagePath);
ByteBuffer ByteBuffer=ByteBuffer.allocate(inputStream.available());
inputStream.getChannel().read(byteBuffer);
byteArrayOutputStream.write(byteBuffer.array());
}捕获(IOE异常){
e、 printStackTrace();
}
返回byteArrayOutputStream.toByteArray();
}
私有静态int-calculateInSampleSize(BitmapFactory.Options选项、int-reqWidth、int-reqHeight){
/*最终内部高度=options.outHeight;
最终整数宽度=options.outWidth;
int inSampleSize=1;
如果(高度>要求高度| |宽度>要求宽度){
最终int半高=高度/2;
最终整数半宽度=宽度/2;
//计算最大的inSampleSize值,该值为2的幂次方,并同时保持这两个值
//高度和宽度大于请求的高度和宽度。
而((半高/采样)>=reqHeight
&&(半宽/采样尺寸)>=reqWidth){
inSampleSize*=2;
}
}*/
最终内部高度=options.outHeight;
最终整数宽度=options.outWidth;
int inSampleSize=1;
如果(高度>要求高度| |宽度>要求宽度){
最终内部高度比=数学圆((浮动)高度/(浮动)要求高度);
最终整数宽度比=数学圆((浮动)宽度/(浮动)宽度);
inSampleSize=高度比<宽度比?高度比:宽度比;
}
最终浮点总数像素=宽度*高度;
最终浮点totalReqPixelsCap=reqWidth*reqHeight*2;
而(totalPixels/(inSampleSize*inSampleSize)>totalReqPixelsCap){
inSampleSize++;
}
返回样本大小;
}
@凌驾
public void onResponse(NetworkResponse){
Toast.makeText(这是“成功”,Toast.LENGTH_SHORT).show();
删除文件();
stopSelf();
}
@凌驾
公共无效onErrorResponse(截击错误){
Toast.makeText(这是“onErrorResponse:+error.getMessage(),Toast.LENGTH\u SHORT.show();
Log.e(标记“onErrorResponse:+error.getMessage());
//stopSelf();
}
私有void deleteFiles(){
实用工具.deleteFolder(NetworkMonitoringService.this,chassisNo);
//实用工具.deleteFolder(NetworkMonitoringService.this,chassisNo);
}
私有void sendImagesToServer(){
HashMap params=新的HashMap();
byteData=新HashMap();
SharedReferences首选项=GetSharedReferences(常量.LOGIN\u数据\u首选项,模式\u私有);
参数put(“docLocation”,docLocation);
参数put(“uniqueNo”,pickupUniqueNumber);
参数put(“国家代码”,常量。国家代码);
params.put(“companyId”,preferences.getString(ConstantsSharedPrefs.PREFS\u KEY\u COMPANY\u ID,”)