我试图设计一个启动相机意图的应用程序,上传照片,(希望正在进行中:从服务器解析XML响应,然后转移到另一个活动并填写一些表单字段)。
问题是到目前为止上传代码是在第一次运行应用程序时执行的,第二次被跳过,第三次正常,第四次跳过,依此类推。
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// buttons
Button lunchCamBtn = (Button) findViewById(R.id.lunchVerBtn);
lunchCamBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
}
});
Button lunchCaptBtn = (Button) findViewById(R.id.lunchCaptBtn);
lunchCaptBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
String path;
String picfname;
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Random rnd = new Random(System.currentTimeMillis());
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Date date = new Date();
String picfname = "bul "+dateFormat.format(date)+" "+rnd.nextInt(90)+".png";
File output = new File(dir,picfname);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(output));
path = output.getAbsolutePath();
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(getApplicationContext(), path.toString(),
Toast.LENGTH_LONG).show();
UploadFiles upld =new UploadFiles(MainActivity.this);
upld.execute(path.toString());
}
public class UploadFiles extends AsyncTask<String, Integer, Boolean> {
WeakReference<Activity> mActivityReference;
public UploadFiles(Activity activity){
this.mActivityReference = new WeakReference<Activity>(activity);
}
@Override
protected Boolean doInBackground(String... params) {
Boolean succesz = true;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String selectedPath = params[0];
String pathToOurFile = selectedPath;
String urlServer = "http://192.168.0.104/upload2.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
try {
Bitmap bmp = BitmapFactory.decodeFile(pathToOurFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
InputStream fileInputStream = new ByteArrayInputStream(bos.toByteArray());
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setChunkedStreamingMode(1024);
connection.setReadTimeout(25000 /* milliseconds */);
connection.setConnectTimeout(30000 /* milliseconds */);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
InputStream stream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
String line = "";
line = convertStreamToString(stream);
System.out.print(line);
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (Exception ex) {
}
return succesz;
}
private String convertStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (Exception e) {
//Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
}
return total.toString();
}
@Override
protected void onPostExecute(Boolean result) {
if (result && mActivityReference.get() != null) {
Activity activity = mActivityReference.get();
Intent iinent= new Intent(activity,TestActivity.class);
activity.startActivity(iinent);
//activity.finish();
}
}}
我现在知道这个问题是由类UploadFiles中的convertStreamToString
方法引起的,但我无法理解究竟是什么导致它。当我完全删除它一切正常。提前谢谢!
答案 0 :(得分:0)
第一个小问题:
使用available
基本上是错误的,尽管它可能有用。
第二个小问题: 不要在这里使用DataOutputStream。我想这是为了能够将字符串写入OutputStream。
response.setContentType(&#34; ...; charset = Windows-1252&#34;); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(os,&#34; Windows-1252&#34;));
以某种方式指定编码/字符集可能会有所帮助。
convertStreamToString的问题: 在没有额外的编码参数添加到InputStreamReader时,使用默认的平台编码。 Android上的UTF-8。那会相对较快失败。
您可能会尝试使用不太严格的单字节编码来查看会发生什么:
BufferedReader rd = new BufferedReader(new InputStreamReader(is, "Windows-1252"));
通常不处理编码:URLConnection.getContentEncoding()
可能提供信息。
答案 1 :(得分:0)
你这里做错了几件事。
不要将异常块留空。它隐藏了所有错误。使用Log.e打印它。
不要使用System.out.println。使用Log。*仅用于记录。
不要使用AsyncTask上传文件。请改用IntentService。并使用localbroadcastmanager广播上传事件为您的活动收听。它将更加友好的配置更改。
而不是自己做所有这些文件上传巫术。请改用httpmime库。它在android上运行起来非常棒。我用我的应用程序进行生产。你需要这样做。
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlToUpload);
MultipartEntity entity = new MultipartEntity();
Bitmap bmp = BitmapFactory.decodeFile(sourceFileUri);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 50, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody imageContent = new InputStreamBody(in, "image/jpeg", sourceFile.getName());
entity.addPart("file", imageContent);
post.setEntity(entity);
HttpResponse response = client.execute(post);
您将获得所有回复&#39;给你看。
String responseBody = EntityUtils.toString(response.getEntity());
您可以从此处下载此库http://repo1.maven.org/maven2/org/apache/httpcomponents/httpmime/4.2.5/
答案 2 :(得分:0)
我已使用此https://github.com/alexbbb/android-upload-service进行文件上传。
我处理广播接收器中所有与响应相关的逻辑,我正在等待上传响应。