从android上传图片到php服务器的问题

时间:2011-05-10 06:27:53

标签: android

大家好 我正在尝试将图像文件从SD卡上传到android中的php服务器。我使用以下代码进行上传,它不显示异常,但图像未上传到服务器中。我不知道是什么问题。请帮助我我附上了我的代码和Logcat信息。 代码:

public class UploadImage extends Activity {
InputStream is;
private int serverResponseCode;
private String serverResponseMessage;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "//sdcard//chsevtoneta.png";
String urlServer = "http://xxxxxxxxxxxxxxxxxxxxxxxx/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();

// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);

// Enable POST method
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=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + 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)

serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
Log.e("response",""+serverResponseCode);
Log.e("serverResponseMessage",""+serverResponseMessage);

fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
}
}

和Logcat信息:

 05-10 11:04:59.762: ERROR/response(2203): 200
 05-10 11:04:59.762: ERROR/serverResponseMessage(2203): OK

2 个答案:

答案 0 :(得分:2)

远程服务器以成功(200)消息回答。我认为错误可能在服务器端,但您没有为此部分提供任何代码。

答案 1 :(得分:1)

查看您的来源,您似乎正在手动构建多部分/表单上传:这很容易出错,在错误的位置添加换行符或额外空间将很难通过眼睛看到很容易混淆服务器(取决于使用的HTTP解析器的严格程度)。

我建议使用Android的内置HTTP组件来完成它:例如http://indiwiz.com/2009/02/11/multi-part-content-upload-in-apache-http-components-http-client/