Php 使用HTTP POST请求从android向服务器上传图像
我想从我的android应用程序上传一张图片到服务器上。我不知道我正在使用的代码中到底是哪里出了问题-它应该可以工作!-。这是我第一次这样做,所以我对它知之甚少 代码没有捕获任何异常,但它从未进入服务器响应为“200”的if语句。。而且图像从未上传 你能回答以下问题吗 1) 这个属性意味着什么Php 使用HTTP POST请求从android向服务器上传图像,php,android,post,Php,Android,Post,我想从我的android应用程序上传一张图片到服务器上。我不知道我正在使用的代码中到底是哪里出了问题-它应该可以工作!-。这是我第一次这样做,所以我对它知之甚少 代码没有捕获任何异常,但它从未进入服务器响应为“200”的if语句。。而且图像从未上传 你能回答以下问题吗 1) 这个属性意味着什么 conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id); 2) 这句话的意思是什么?我知道它将使用数据输出流写入服务器,但其中的参数
conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id);
2) 这句话的意思是什么?我知道它将使用数据输出流写入服务器,但其中的参数是什么
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+
user_id+ lineEnd);
===========
public void upload_to_server(File [] sdDirList, int fileIndex) throws IOException
{
final ProgressDialog dialog = ProgressDialog.show(SettingsActivity.this, "", "Uploading Image...", true);
final String upLoadServerUri = "server side php script goes here";
//***File path ***//
final String uploadFilePath = sdDirList[fileIndex].getCanonicalPath();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, uploadFilePath,
Toast.LENGTH_SHORT).show();
}
});
//***Display the dialog of the upload state***//
new Thread(new Runnable()
{
//Sending thread
public void run()
{
dialog.show();
String fileName = uploadFilePath;
int serverResponseCode = 0;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(uploadFilePath);
if (!sourceFile.isFile())
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "File is not valid..",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
return;
}
else
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "Entered else block",
Toast.LENGTH_SHORT).show();
}
});
try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+
user_id+ lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "reached reponses's if",
Toast.LENGTH_SHORT).show();
}
});
if(serverResponseCode == 200)
{
runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(SettingsActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "End of Try",
Toast.LENGTH_SHORT).show();
}
});
}
catch (MalformedURLException ex)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "in first catch",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
}
catch (Exception e)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "in second catch",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "Something went wrong..",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "end of else",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
} // End else block
}
}).start();
}
============================
public void upload_to_server(File [] sdDirList, int fileIndex) throws IOException
{
final ProgressDialog dialog = ProgressDialog.show(SettingsActivity.this, "", "Uploading Image...", true);
final String upLoadServerUri = "server side php script goes here";
//***File path ***//
final String uploadFilePath = sdDirList[fileIndex].getCanonicalPath();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, uploadFilePath,
Toast.LENGTH_SHORT).show();
}
});
//***Display the dialog of the upload state***//
new Thread(new Runnable()
{
//Sending thread
public void run()
{
dialog.show();
String fileName = uploadFilePath;
int serverResponseCode = 0;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(uploadFilePath);
if (!sourceFile.isFile())
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "File is not valid..",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
return;
}
else
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "Entered else block",
Toast.LENGTH_SHORT).show();
}
});
try
{
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", "Thumbnail"+user_id);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+
user_id+ lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "reached reponses's if",
Toast.LENGTH_SHORT).show();
}
});
if(serverResponseCode == 200)
{
runOnUiThread(new Runnable() {
public void run()
{
Toast.makeText(SettingsActivity.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "End of Try",
Toast.LENGTH_SHORT).show();
}
});
}
catch (MalformedURLException ex)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "in first catch",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
}
catch (Exception e)
{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "in second catch",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "Something went wrong..",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(SettingsActivity.this, "end of else",
Toast.LENGTH_SHORT).show();
}
});
dialog.dismiss();
} // End else block
}
}).start();
}
PHP脚本:
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
1)
有两个参数
第一个参数:它是在php文件中定义的变量名(必须与php文件中定义的相同),用于获取文件
第二个参数:您要上传的文件
(二)
它类似于传递给DataOutputStream
的查询字符串。。在这里,您将通过变量(您在上面定义的)和该文件的文件名传递文件
这里,,
upload_file
是在服务器(php)和
name
&filename
是字段名(不要更改)…您可以根据需要更改其值
如果您想要上传文件的教程,请访问以下链接:
谢谢…文件上载代码:
String upLoadServerUri_here = "Your url " ;
private int serverResponseCode = 0;
private Context mContext ;
public int upload_to_server(final String imagepath) {
String fileName = imagepath;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024 ;
File sourceFile = new File(imagepath);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" + imagepath);
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "Source File not found "+imagepath ,Toast.LENGTH_LONG).show();
}
});
return 0;
}
else
{
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri_here);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "attachment");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
//create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
Toast.makeText(mContext, "Got.."+serverResponseMessage, Toast.LENGTH_SHORT).show();
if(serverResponseCode == 200){
//chk it @ C:\inetpub\wwwroot\Uploads\Work
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "sucesss..", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
// dialog.dismiss();
ex.printStackTrace();
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "Got Exception : see logcat "+serverResponseCode, Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
return serverResponseCode;
}
}
其中imagepath=“yourselectedimage with full path” void java.net.URLConnection.setRequestProperty(String字段,String newValue)public void setRequestProperty(String字段,String newValue)设置指定请求头字段的值。该值将仅由当前URLConnection实例使用。只能在建立连接之前调用此方法。参数字段要设置的请求标头字段。newValue指定属性的新值。如果已建立连接,则引发IllegalStateException。如果参数字段为null,则为NullPointerException。感谢您的回复,我现在理解了request属性,这要感谢您&prag的回答,但您发布的代码几乎相同,我对其进行了修改&writeByte(content…)中只有一个不同之处,你能告诉我我在代码中犯的错误吗?谢谢..你的文件在正确获取文件之前不会返回“Success”,该文件是用php编写的,如果(move_uploaded_file($_FILES['uploaded_file']['tmp_name',$file_path]),那么请签入writeByte(content…)关于更多细节,chk我想询问更多关于writeBytes的信息;参数值是否与“setRequestProperty”相关?是否与“filename=…”相关。。“必须与我要上载的文件匹配,还是类似于重命名?对不起,我有点困惑;由于源文件已作为输入流传递..非常感谢您提供的链接&您的答案:)。您不应更改“filename=”属性。。这将导致上传错误…所有文件都是一样的…很高兴能帮上忙+1为它……)它现在可能可以工作了,我没有改变文件名&在服务器的uploads文件夹中添加了一个缺少的“777”权限。再次感谢您的回答。非常感谢,如果原始代码不起作用,我将使用这个库,它看起来更加封装和可读。
dos.writeBytes("Content-Disposition: form-data; name=uploaded_file;filename=Thumbnail"+ user_id+ lineEnd);
String upLoadServerUri_here = "Your url " ;
private int serverResponseCode = 0;
private Context mContext ;
public int upload_to_server(final String imagepath) {
String fileName = imagepath;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024 ;
File sourceFile = new File(imagepath);
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" + imagepath);
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "Source File not found "+imagepath ,Toast.LENGTH_LONG).show();
}
});
return 0;
}
else
{
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri_here);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "attachment");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
//create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
Toast.makeText(mContext, "Got.."+serverResponseMessage, Toast.LENGTH_SHORT).show();
if(serverResponseCode == 200){
//chk it @ C:\inetpub\wwwroot\Uploads\Work
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "sucesss..", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
// dialog.dismiss();
ex.printStackTrace();
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
((Activity) mContext).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mContext, "Got Exception : see logcat "+serverResponseCode, Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
return serverResponseCode;
}
}