gpt4 book ai didi

android - 如何将图像添加到网络服务器

转载 作者:行者123 更新时间:2023-11-30 04:42:25 24 4
gpt4 key购买 nike

这里我要上传图片到网站

我列出了它的代码,但它不起作用。

所以请帮我改正这个。

MyImageUploader.java

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MyImageUploader extends Activity{
private static final int PICK_IMAGE = 1;
private ImageView imageview;
private TextView textview;
private Button button;
private EditText edittext;
private Bitmap bitmap;
private ProgressDialog dialog;
String albumId = ConstantData.album_id;
Integer userId = ConstantData.userId;
Bitmap photoId;
ArrayList<Object> result;
XmlParser parser;
HttpResponse response;
InputStream in;
String strResponse;
HttpPost post;
int width_tmp,height_tmp;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myimageuploader);

imageview = (ImageView)findViewById(R.id.upldimgvw);
button = (Button)findViewById(R.id.btn_imgupld);
edittext = (EditText)findViewById(R.id.edt_cptn);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(bitmap == null){
Toast.makeText(getApplicationContext(), "Please select image..", Toast.LENGTH_SHORT).show();
}
else{
dialog = ProgressDialog.show(MyImageUploader.this, "Uploading", "Please wait...",true);
new ImageUploadTask().execute();
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.imageupload_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_menu_gallery:
try{
Intent intent = new Intent();
intent.setType("Image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE);
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "Get Picture" ,Toast.LENGTH_SHORT).show();
Log.e(e.getClass().getName(),e.getMessage(),e);
break;
}
return true;
case R.id.ic_menu_Images:
Toast.makeText(this, "You pressed the Image!", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}

protected void onActivityResult(int requestcode,int resultcode, Intent data){
Log.i("Request Code",""+requestcode);
Log.i("Result Code", ""+resultcode);
Log.i("Intent Data",""+data);
switch(requestcode){
case PICK_IMAGE:
if(resultcode == Activity.RESULT_OK);
Uri selectedImageUri = data.getData();
String filePath = null;
try{
String filemanagerstring = selectedImageUri.getPath();
String selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath != null)
{
filePath = selectedImagePath;
}else if(filemanagerstring != null)
{
filePath = filemanagerstring;
}else{
Toast.makeText(getApplicationContext(), "Unknown Path",Toast.LENGTH_SHORT).show();
Log.e("Bitmap","Unknown Path");
}
if(filePath != null){
decodeFile(filePath);
}
else{
bitmap = null;
}
}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(), "Internal Error", Toast.LENGTH_SHORT);
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}

}

class ImageUploadTask extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
DefaultHttpClient client = new DefaultHttpClient();
post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=album_list&upload_photo&userid=80&sessionid=3011e063260d55b8a7095bc3a581130c&tmpl=component 14:34");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><photo>"+photoId+"</photo></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addpart("userId");
entity.addPart("albumId");
entity.addPart("photoId", new FileBody(new File(filepath)));
post.setEntity(entity);
response = client.execute(post);
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "photo");
}catch (Exception e){
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),"image",Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
return albumId;
}
}
protected void onPostExecution(String strResponse){
try{
if(dialog.isShowing())
dialog.dismiss();
if(strResponse != null)
{
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Photo Uploaded Successfully", Toast.LENGTH_SHORT).show();
edittext.setText("");
}


}catch (Exception e) {
// TODO: handle exception
Toast.makeText(getApplicationContext(),"Exception Image", Toast.LENGTH_SHORT).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}


public String getPath(Uri uri){
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor != null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else{
return null;
}
}
public void decodeFile(String filePath){
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath,o);

final int REQUEST_SIZE = 1024;
int width_tmp = o.outWidth,height_tmp = o.outHeight;
int scale = 1;
while(true){
// if(width_tmp &lt;REQUEST_SIZE &amp;&amp; height_tmp &lt; REQUEST_SIZE){
//break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
// }
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath,o2);
imageview.setImageBitmap(bitmap);
}

}
public String convertStreamToString(InputStream in)
throws IOException {


if (in != null) {
Writer writer = new StringWriter();

char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}

谢谢。

最佳答案

使用此功能上传。请将您的文件路径作为参数传递。

public void uploadImage(String fileName)
{
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;

String pathToOurFile = fileName;
String urlServer = GlobalHandler.getImageUploadUrl();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();

// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);

// Enable POST method
connection.setRequestMethod("POST");

connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
if(GlobalHandler.getUserId()!=null)
connection.addRequestProperty("user_id", GlobalHandler.getUserId());
else
connection.addRequestProperty("user_id", "007");

outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"upload_file\"; filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// Read file
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);

// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling

}

}

关于android - 如何将图像添加到网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5727941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com