您正在开发一个需要以jpeg格式将一些图像以多部分文件形式发布到服务器的应用程序,我已经在下面给出了代码,但它给出了以下响应,
01-15 00:32:14.119: I/System.out(7598): file is upload {"status":"error","message":"Please, Specify valid Parameter for file"}
请某人帮助我。提前致谢 。
这是我的活动代码
public class SendPostActivity extends Activity implements OnClickListener {
private Context appContext;
private String messageType;
HashMap<String, String> fileList = new HashMap<String, String>();
public String finalImagePath = null;
// number of images to select
private static final int PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
setContentView(R.layout.activity_send_post);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
appContext = this;
initComponent();
}
private void initComponent() {
((Button) findViewById(R.id.btnLeftNav)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.btnRightNav)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.btnRightNav))
.setBackgroundResource(R.drawable.send_btn);
((Button) findViewById(R.id.btnLeftNav)).setOnClickListener(this);
((Button) findViewById(R.id.btnRightNav)).setOnClickListener(this);
((ImageView) findViewById(R.id.imageviewCamera))
.setOnClickListener(this);
((ImageView) findViewById(R.id.imageviewGallery))
.setOnClickListener(this);
((TextView) findViewById(R.id.txtAudioSong)).setOnClickListener(this);
((TextView) findViewById(R.id.txtVedioSong)).setOnClickListener(this);
Typeface face = Typeface.createFromAsset(getAssets(),
"fonts/GeosansLight.ttf");
((TextView) findViewById(R.id.txtHeading)).setTypeface(face);
((EditText) findViewById(R.id.edtMessage)).setTypeface(face);
((TextView) findViewById(R.id.txtHeading)).setText("Send Post");
}
@Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btnLeftNav) {
this.finish();
} else if (v.getId() == R.id.btnRightNav) {
String strPostMessage = ((EditText) findViewById(R.id.edtMessage))
.getEditableText().toString().trim();
if (strPostMessage.length() == 0) {
Toast.makeText(appContext, "Type message.", Toast.LENGTH_LONG)
.show();
} else {
messageType = "text";
}
}
// on this button click i want to post images to server
else if (v.getId() == R.id.imageviewCamera) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
} else if (v.getId() == R.id.imageviewGallery) {
/*
* Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
* intent.setType("image/*"); startActivityForResult(intent, 2);
*/
selectImageFromGallery();
} else if (v.getId() == R.id.txtAudioSong) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("audio/*");
startActivityForResult(intent, 3);
} else if (v.getId() == R.id.txtVedioSong) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("video/*");
startActivityForResult(intent, 4);
}
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
}
public void decodeFile(String filePath) {
// Decode image size
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);
if (bitmap != null) {
new ImageUploadTask().execute();
}
}
private Bitmap bitmap;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
decodeFile(picturePath);
}
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
// private String webAddressToPost = "http://your-website-here.com";
// private ProgressDialog dialog;
private ProgressDialog dialog = new ProgressDialog(
SendPostActivity.this);
@Override
protected void onPreExecute() {
dialog.setMessage("Uploading...");
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(Constant.serverUrl
+ "PostComment");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String file = Base64.encodeToString(data, Base64.DEFAULT);
entity.addPart("file", new StringBody(file));
entity.addPart(
"user_id",
new StringBody(Utility.getSharedPreferences(appContext,
Constant.USER_ID)));
entity.addPart(
"msg_id",
new StringBody(Utility.getSharedPreferences(appContext,
Constant.MESSAGE_ID)));
entity.addPart("type", new StringBody("image"));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
if (response != null) {
finalImagePath = sResponse;
}
return sResponse;
} catch (Exception e) {
// something went wrong. connection with the server error
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "file uploaded",
Toast.LENGTH_LONG).show();
System.out
.println("file is uploaded ////////////" + finalImagePath);
}
} // asyntask class ends
} // final class ends
这是我的服务器api方法:
function PostComment()
{
$obj = new funcs_code();
$obj->connection();
$output = "";
$uid = mysql_real_escape_string($_REQUEST['user_id']);
$mid = mysql_real_escape_string($_REQUEST['msg_id']);
$comm = "";
$type = "text";
if(isset($_REQUEST['type']))
{
$type = mysql_real_escape_string($_REQUEST['type']);
}
if(isset($_REQUEST['comment']))
{
$comm = mysql_real_escape_string($_REQUEST['comment']);
}
$sql = "SELECT * FROM `users` WHERE user_id = '$uid'";
$res = mysql_query($sql);
if(mysql_num_rows($res)==1)
{
$row = mysql_fetch_assoc($res);
$sql1 = "SELECT * FROM `messages` WHERE msg_id = '$mid'";
$res1 = mysql_query($sql1);
if(mysql_num_rows($res1)==1)
{
$row1 = mysql_fetch_assoc($res1);
if($row['group_id'] == $row1['groupId'])
{
$status = 1; // 1 for comment
$fileName = "";
if(isset($_FILES['file']) && is_array($_FILES['file']))
{
$allowedExts = array("jpeg", "jpg", "mp3", "mp4", "3gp");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
//
//Check File Extension & Size UPTO 5 MB
//
if (( $_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "audio/mpeg"
|| $_FILES["file"]["type"] == "video/3gpp" || $_FILES["fiile"]["type"] == "video/mp4" ) && $_FILES["file"]["size"] < 5242880 && in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
//echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
$output = array('status' => 'error','message' => $_FILES["file"]["error"]);
header('content-type: application/json');
echo json_encode($output);
exit;
}
else
{
$fileName = time().".$extension";
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/". $fileName);
$fileName = '/uploads/'.$fileName;
}
}
else
{
$output = array('status' => 'error','message' => "Invalid_File");
header('content-type: application/json');
echo json_encode($output);
exit;
}
if($fileName != '' && $type != 'text')
{
$comm = $fileName;
}
}
//
//Below Condition Used to check, If uploading any media and File not Uploaded
//
if($type != 'text' && $fileName == ""){
$output = array('status' => 'error','message' => "Please, Specify valid Parameter for file");
header('content-type: application/json');
echo json_encode($output);
exit;
}
//
//In Any Case Comment can not be left blank
//
if($comm != "")
{
$sq = "INSERT INTO `user_comment`(`user_id`,`msg_id`,`type`,`comment`,`status`) VALUES('$uid','$mid','$type','$comm','$status')";
if(mysql_query($sq))
$output = array('status' => 'success','message' => "Comment_Success");
else
$output = array('status' => 'error','message' => "Comment_Fail");
}else{
$output = array('status' => 'error','message' => "Comment Can not be blank");
header('content-type: application/json');
echo json_encode($output);
exit;
}
///////////////////////////
}// group
else
{
//$output = 'user_group not match';
$output = array('status' => 'error','message' => "User_group_Not_match");
}
}
else
{
//$output = 'invalid msg_id';
$output = array('status' => 'error','message' => "Invalid_Msg_id");
}
}
else
{
//$output = "invalid user_id";
$output = array('status' => 'error','message' => "Invalid_User");
}
header('content-type: application/json');
echo json_encode($output);
}
答案 0 :(得分:3)
类型错误,此行应为image/jpeg
:
entity.addPart("type", new StringBody("image"));
另外,您要将File
作为Base 64编码的字符串发送?你确定php代码可以处理吗?通常你应该直接使用FileBody
和文件,但你可以使用ContentBody
作为字节数组。
这是我使用ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), "image/jpeg", "file.jpg");
mpEntity.addPart("file", contentPart);
这是您使用FileBody
File f = ....
mpEntity.addPart("file", new FileBody(f));
答案 1 :(得分:0)
从“服务器api方法”
if($type != 'text' && $fileName == ""){
$output = array('status' => 'error','message' => "Please, Specify valid Parameter for file");
header('content-type: application/json');
echo json_encode($output);
exit;
}
这意味着$ type不等于'text',$ fileName等于“”。所以,请转到这一行:
改变这个:
$fileName = time().".$extension";
进入这个:
$fileName = time().'.'.$extension";
然后让我知道发生了什么。