问题描述
我正在开发一个Android应用程序,该应用程序使用PHP和okhttp将图像上传到指定目录。好吧,前端和后端在我的个人设备上都可以正常工作,但是在非三星设备上崩溃。
研究问题时,我发现服务器返回了:
com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@17768aa).inputStream() 在非三星设备上。
文件Upload的Java代码如下:
public class UploadGalleryStoryPost {
private Context context;
private String fileName = "",User_Id = "",Type="";
private ProgressDialog progressDialog;
private int serverResponseCode = 0;
private String count = "";
private String fileCount = "";
public UploadGalleryStoryPost(String fileName,Context context,String User_Id,String Type,String count,String fileCount) {
this.fileName = fileName;
this.context = context;
this.User_Id = User_Id;
this.Type = Type;
this.count = count;
this.fileCount = fileCount;
new UploadingGalleryPost().execute();
}
private class UploadingGalleryPost extends AsyncTask<Void,Void,Void> {
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead,bytesAvailable,bufferSize;
byte[] buffer;
int maxBufferSize =1024 * 1024;
File sourceFile_profile = new File(fileName);
private String upLoadServerUri = APP_SERVER_URL+"AddAStory.php";
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(context);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected void onPostExecute(Void result) {
try{
if(serverResponseCode == 200){
int count1 = Integer.parseInt(count);
int fileCount1 = Integer.parseInt(fileCount);
Log.e("value"," "+ String.valueOf(count1-1)+" "+fileCount1);
if((fileCount1-1) == count1) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context,R.style.myDialog);
builder1.setCancelable(false);
builder1.setTitle("Alert!");
builder1.setMessage("Uploaded successfully.");
builder1.setPositiveButton("OK",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int which) {
dialog.dismiss();
Intent i = new Intent(context,DashBoard.class);
context.startActivity(i);
}
});
AlertDialog dialog1 = builder1.create();
dialog1.show();
}
else {
progressDialog.dismiss();
Toast.makeText(context,fileName+" has been uploaded successfully",Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,"Got Exception : see logcat ",Toast.LENGTH_SHORT).show();
Log.e("UploadtoserverException","Exception : "
+ e.getMessage(),e);
}
super.onPostExecute(result);
}
@Override
protected Void doInBackground(Void... voids) {
try{
// open a URL connection to the Servlet
FileInputStream fileInputStream_profile = new FileInputStream(sourceFile_profile);
URL url = new URL(upLoadServerUri);
// 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.setChunkedStreamingMode(1024);
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("ENCTYPE","multipart/form-data");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("Attachment",fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Attachment\";filename=\""+fileName+"\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream_profile.read(buffer,bufferSize);
while (bytesRead > 0) {
dos.write(buffer,bufferSize);
bytesAvailable = fileInputStream_profile.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream_profile.read(buffer,bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"User_Id\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(User_Id);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"Type\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Type);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
conn.getErrorStream();
Log.e("uploadFile","HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode+" "+ conn.getErrorStream());
//close the streams //
fileInputStream_profile.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server","error: " + ex.getMessage(),ex);
} catch (Exception e) {
e.printStackTrace();
Log.e("UploadtoserverException",e);
}
return null;
}
}
}
php代码为:
<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('Y-m-d H:i:s');
$new_time = date("Y-m-d H:i:s",strtotime('+24 hours'));
$day = date("l");
$response = array();
include 'db_connect.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$User_Id = $_POST['User_Id'];
$Story_Content = $_POST['Story_Content'];
$B_Id = $_POST['B_Id'];
$Type = $_POST['Type'];
if($Type == 'BGTXT'){
$sql = "INSERT INTO Story_Common(User_Id,Timestamp_Start,Status,Timestamp_End)
VALUES('$User_Id','$date','Open','$new_time')";
$result = sqlsrv_query($conn,$sql);
if($result){
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn,$sql1);
if (sqlsrv_has_rows($res1) == true)
{
while ($row_sql1 = sqlsrv_fetch_array($res1,SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story(Story_Id,Story_Content,B_Id)
VALUES('$Story_Id',N'$Story_Content','$B_Id')";
$result2 = sqlsrv_query($conn,$sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else if($Type == 'Photo/Video'){
$sql = "INSERT INTO Story_Common(User_Id,$sql);
if($result){
if (empty($_FILES["Attachment"]["name"])) {
$path = "NA";
}
else {
$Attachment=$_FILES["Attachment"]["name"];
$temp=$_FILES["Attachment"]["tmp_name"];
$tst= time();
$url = "Post_Media/" . $tst . $Attachment;
$path="http://kidsfb.kidsfb.com/ver1PHP/".$url;
move_uploaded_file($temp,$url);
}
$sql1 = "SELECT TOP 1 * FROM Story_Common ORDER BY Story_Id DESC";
$res1 = sqlsrv_query($conn,SQLSRV_FETCH_BOTH))
{
$Story_Id = $row_sql1["Story_Id"];
}
}
$sql2 = "INSERT INTO Story_Media(Story_Id,Media_Att)
VALUES('$Story_Id','$path')";
$result2 = sqlsrv_query($conn,$sql2);
if($result2){
$response['success'] = 200;
$response['message'] = "Insert in db success.";
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
else{
$response['success'] = 0;
$response['message'] = "Failed to insert db.";
}
}
echo json_encode($response);
}
?>
尝试将缓冲区大小从1024增加到2048仍然无法在其他设备上使用。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)