Я написал код, который снимает изображение с устройства Android, а затем загружает его на сервер. Может также загрузить рис из галереи. Загрузка из галереи работает отлично. Она может намереваться мобильную камеру при нажатии кнопки захвата, но когда я вернусь, у меня не получилось никакого изображения, и когда я проверил галерею, изображение не было захвачено.Загрузка android на сервер с помощью multipartentity
Got menifest разрешение также
android.permission.WRITE_EXTERNAL_STORAGE"
android.permission.READ_EXTERNAL_STORAGE"
android.permission.CAMERA"
Это код в моем Фрагменты onCreateView() класса:
mTakePhoto = (Button) rootView.findViewById(R.id.take_photo);
mselectPhoto = (Button) rootView.findViewById(R.id.select_photo);
mImageView = (ImageView) rootView.findViewById(R.id.imageview);
mTakePhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
TAKE_PICTURE);
}
});
mselectPhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,
IMAGE_PICKER_SELECT);
}
});
В приведенном выше коде я думаю, что намерения отлично работает
В сильфона коде, условие (requestCode == IMAGE_PICKER_SELECT) работает отлично. Но, похоже, я не получил каких-либо данных, когда я сфотографировал
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == IMAGE_PICKER_SELECT
&& resultCode == Activity.RESULT_OK) {
Bitmap bitmap = getBitmapFromCameraData(data, getActivity());
int nh = (int) (bitmap.getHeight() * (512.0/bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(bitmap);
}
if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK
&& data != null) {
// get bundle
Bundle extras = data.getExtras();
// get bitmap
cameraBitmap = (Bitmap) extras.get("data");
int nh = (int) (cameraBitmap.getHeight() * (512.0/cameraBitmap
.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(cameraBitmap, 512, nh,
true);
mImageView.setImageBitmap(scaled);
new UploadTask().execute(cameraBitmap);
// setPic();
}
}
Я м также дает код моего Multipartentity класса
public class MultipartEntity implements HttpEntity {
enter code here
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
@Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
@Override
public boolean isChunked() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
@Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
я м застрял на почти полный день. Помогите!!
У вас возникли какие-либо ошибки при съемке фотографии с камеры? –
Нет ошибки. Нет выхода. nathing –
hmmm okay, вы уверены, что ваш код находится внутри этой строки: if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK && data! = null) –