我正在尝试从我的应用程序上传图像,web服务工作正常,因为我尝试使用POSTMAN客户端上传图像。我试图在stackoverflow中搜索,但还没有运气。如果有人可以帮助我。提前谢谢。
FragmentTab1.java
public class FragmentTab1 extends Fragment {
Button postAd, browse;
EditText discription;
EditText price;
String discriptionText;
String priceText;
String adTypetext;
RadioGroup adType;
RadioButton buy;
RadioButton sell;
Bitmap bitmap;
ProgressDialog dialog;
String encodedImage;
String userid;
JSONArray AdsArray = null;
String TAG_ID = "id";
String TAG_IMAGE = "image";
String TAG_TYPE = "adType";
String TAG_DISCRIPTION = "description";
String TAG_PRICE = "price";
String TAG_COUNTER = "counter";
ListView lv;
Switch myswitch;
ProgressDialog progressDialog;
final Context context = getActivity();
ArrayList<HashMap<String, String>> adList;
private static final int PICK_IMAGE = 1;
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.e("onCreateView", "entry1");
View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
postAd = (Button) rootView.findViewById(R.id.bpostAd);
discription = (EditText)rootView.findViewById(R.id.etDiscription);
price = (EditText)rootView.findViewById(R.id.etPrice);
browse = (Button)rootView.findViewById(R.id.bBrowse);
lv = (ListView)rootView.findViewById(R.id.listView1);
SharedPreferences mPrefs = getActivity().getSharedPreferences("IDvalue", 0);
userid = mPrefs.getString("userIdKey", null);
adList = new ArrayList<HashMap<String, String>>();
new LoadMyAds().execute();
discription.addTextChangedListener(txwatcher);
postAd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
discriptionText = discription.getText().toString();
priceText = price.getText().toString();
if (encodedImage == null) {
Toast.makeText(getActivity().getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
new ImageUploadTask().execute();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.postAd(encodedImage,
discriptionText, adTypetext, priceText, userid);
try {
if (json.getString("status") != null) {
String res = json.getString("status");
if (Integer.parseInt(res) == 1) {
Toast.makeText(getActivity().getApplicationContext(),
"Ad has been posted", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"posting error", Toast.LENGTH_LONG)
.show();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
});
browse.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent(); intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.e("onActivity Result", "Image");
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getActivity().getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Log.e("getPath", "entry3");
@SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
Log.e("decodeFile", "entry4");
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
Log.e("Decodefile", "bitmap set");
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.e("ImageUpload", "entry5");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
// encodedImage = new String(data);
encodedImage = Base64.encodeToString(data, Base64.DEFAULT);
return encodedImage;
}
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
}
Userfunction.java
public class UserFunctions {
private JSONParser jsonParser;
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
public JSONObject postAd(String encodedImage, String discriptionText,
String adTypetext, String priceText, String userid) {
// TODO Auto-generated method stub
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("image", encodedImage));
params.add(new BasicNameValuePair("description", discriptionText));
params.add(new BasicNameValuePair("adType", adTypetext));
params.add(new BasicNameValuePair("price", priceText));
params.add(new BasicNameValuePair("userId", userid));
JSONObject json = jsonParser.makeHttpRequest(postAdUrl, "POST", params);
return json;
}
}
输出
使用POSTMAN客户端发布了第一个json输出,并且图像已成功上传,因此我认为webservices工作正常。 第二个结果显示使用上面的代码没有任何扩展的图像链接所以我想我在我的代码中做错了。
{
"id": "5",
"image": "http://iphoneappsdevelopment.info/kwebservices/upload/ads/ACK0_YNVY_IKLF.jpg",
"adType": "Buying",
"description": "hskskg",
"price": "100",
"counter": "1",
"adUserId": "9"
},
{
"id": "7",
"image": "http://iphoneappsdevelopment.info/kwebservices/upload/ads/YBR7_3VOG_9ZJN.",
"adType": "Selling",
"description": "sjsj",
"price": "1088",
"counter": "2",
"adUserId": "9"
},