我使用Retrofit将数据上传到服务器,幸运的是我成功上传了一张图片并且工作正常,但在上传音频文件后,它上传了不同的尺寸而无法正常工作。
我按照此tutorial上传了图片。
我添加一些参数来上传音频:
@FormUrlEncoded
@POST("upload.php")
Call<ImageClass> uploadImage(@Field("title") String title, @Field("image") String image, @Field("audio") String audio);
我使用静态uri音频文件:
private String audioPath() {
File file = new File(Environment.getExternalStorageDirectory() + "/Download/audio2.wav");
Uri uri = Uri.fromFile(file);
return uri.toString();
}
这是上传方法:
private void upload() {
String Image = imageToString();
String Title = imageTitle.getText().toString();
String Audio = audioPath();
Log.d("TAG", Audio);
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<ImageClass> call = apiInterface.uploadImage(Title, Image, Audio);
call.enqueue(new Callback<ImageClass>() {
@Override
public void onResponse(Call<ImageClass> call, Response<ImageClass> response) {
ImageClass imageClass = response.body();
Toast.makeText(getApplicationContext(), "Server response: " + response, Toast.LENGTH_SHORT).show();
image.setVisibility(View.GONE);
imageTitle.setVisibility(View.GONE);
choose.setEnabled(true);
upload.setEnabled(false);
imageTitle.setText("");
}
@Override
public void onFailure(Call<ImageClass> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Server response: " + "Fail", Toast.LENGTH_SHORT).show();
}
});
}
在php代码中:
if ($con) {
$title = $_POST['title'];
$image = $_POST['image'];
$audio = $_POST['audio'];
$upload_path = "upload/$title.jpg";
$audio_path = "audio/$title.wav";
$sql = "insert into imageinfo(title,path,audio) values('$title','$upload_path','$audio_path');";
if (mysqli_query($con, $sql)) {
file_put_contents($upload_path, base64_decode($image));
file_put_contents($audio_path, $audio);
echo json_encode(array('response' => "Image uploaded successfully...."));
} else {
echo json_encode(array('response' => "Image uploaded failed...."));
}
mysqli_close($con);
}