Php 使用Android应用程序中的文件和文本发出POST请求
我在从Android应用程序向web服务(Google Cloud和PHP)发出正确的POST请求时遇到了一些问题 当我尝试从Android发送图像时,它会返回“200OK”响应,但图像不会保存在Google云存储的存储桶中。我知道问题出在Android应用程序中我的方法的POST请求上,因为我已经用Postman进行了测试,并使其顺利运行。因此,我的应用程序中的以下代码有问题:Php 使用Android应用程序中的文件和文本发出POST请求,php,android,post,httpurlconnection,Php,Android,Post,Httpurlconnection,我在从Android应用程序向web服务(Google Cloud和PHP)发出正确的POST请求时遇到了一些问题 当我尝试从Android发送图像时,它会返回“200OK”响应,但图像不会保存在Google云存储的存储桶中。我知道问题出在Android应用程序中我的方法的POST请求上,因为我已经用Postman进行了测试,并使其顺利运行。因此,我的应用程序中的以下代码有问题: public void uploadFile(String uploadUrl, String filename,
public void uploadFile(String uploadUrl, String filename, String newFileName) throws IOException {
FileInputStream fileInputStream = new FileInputStream(new File(filename));
URL url = new URL(uploadUrl);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"img\";filename=\"" + filename + "\"" + 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();
System.out.println(serverResponseMessage);
System.out.println(serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
我已经测试过所有参数都是100%正确的,所以你不必担心
如果您需要查看web服务中用于接收请求的PHP代码,请参见:
<?php
$img = $_FILES['img']['tmp_name'];
move_uploaded_file($img, 'gs://routeimages/yeeeeeeees.jpg');
echo "done";
?>
此代码中的问题可能在哪里
附加的
除了文件/图像之外,我还需要添加一些文本。如何将此添加到请求中?为什么不使用截击库?它的方式更容易和干净。像这个例子:
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(MainActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Getting Image Name
String name = editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void uploadImage(){
//显示进度对话框
final ProgressDialog loading=ProgressDialog.show(这是“正在上载…”,“请稍候…”,false,false);
StringRequest StringRequest=新建StringRequest(Request.Method.POST,UPLOAD\u URL,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串s){
//取消进度对话框的限制
loading.dispose();
//显示响应的toast消息
Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG.show();
}
},
新的Response.ErrorListener(){
@凌驾
公共错误响应(截击错误截击错误){
//取消“进度”对话框
loading.dispose();
//敬酒
Toast.makeText(MainActivity.this,volleyError.getMessage().toString(),Toast.LENGTH_LONG.show();
}
}){
@凌驾
受保护的映射getParams()引发AuthFailureError{
//将位图转换为字符串
字符串图像=getStringImage(位图);
//获取图像名称
字符串名称=editTextName.getText().toString().trim();
//创建参数
Map params=新哈希表();
//添加参数
参数put(按键图像,图像);
参数put(键名称、名称);
//返回参数
返回参数;
}
};
//创建请求队列
RequestQueue RequestQueue=Volley.newRequestQueue(this);
//将请求添加到队列
添加(stringRequest);
}
看起来您缺少要发送的图像文件的
内容类型
看看下面发送文件的HTTP Post头
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="pics", filename="file2.gif"
Content-type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif...
--AaB03x--
因此,您需要在代码中添加内容类型
属性,如下所示:
outputStream = new DataOutputStream(connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"img\";filename=\"" + filename + "\"" + lineEnd);
outputStream.writeBytes("Content-type: image/gif" + lineEnd); // or whatever format you are sending.
outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
outputStream.writeBytes(lineEnd);
我希望这段代码能帮助您解决问题
附加:除了文件/图像之外,我还需要添加一些文本。如何将此添加到请求中?
要发送一些额外参数(一些文本),请查看随文本参数一起发送图像的以下http格式:
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-data; name="pics", filename="file2.gif"
Content-type: image/gif
Content-Transfer-Encoding: binary
...contents of file2.gif...
--AaB03x--
content-disposition: form-data; name="field1"
Joe Blow
--AaB03x
我希望您现在可以在上述图像上传说明和此格式的帮助下编写额外参数的代码。name=\“img\”;filename=\“”
我在路径中看到一个分号。为什么呢?无论如何,对于图像上传用户多部分dat。答案中的细节。。。谢谢你的回答。非常感谢。也许稍后我会考虑使用截击LIB,但现在我将坚持“手动”的方法。这是一个关于如何将文件转换为字符串然后发送字符串的一个很好的答案。但问题是如何发送文件。