我正在尝试将图像从Android App上传到带有PHP脚本的服务器。 HTTP响应返回STATUS OK:200,但$ _FILES [“upfile”] [“name”]返回空。 我检查了我的文件夹权限,并且isady是777。
我的.java类
/********************UPLOAD DATA*************************************/
class UploadImg extends AsyncTask<Void, Void, Void>{
NetworkInfo net;
Messaging uActivity;
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String folderPath;
String arrayOfFiles[];
File root;
File allFiles;
String urlServer = "http://bmcpublicidade.com.br/chat/upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10*1024*1024;
URL url;
ProgressDialog pDialog = new ProgressDialog(Messaging.this);
@Override
protected void onPreExecute() {
Log.d(" UploadImg","onPreRequest");
pDialog.setMessage("Uploading GPS Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
Log.d(" UploadData","doInBackground");
String fileName = ""+selectedPath;
HttpURLConnection conn = null;
DataOutputStream dos = null;
BufferedReader inStream = null;
String lineEnd = "rn";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 10*1024*1024;
String responseFromServer = "";
String urlString = "http://bmcpublicidade.com.br/chat/upload.php";
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
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("upfile", fileName);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename='"+ selectedPath +"'" + 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("upfile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://**********/media/uploads/";
messageText.setText(msg);
Toast.makeText(Messaging.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
// close streams
Log.e("Debug","gravando arquivo: " + fileName);
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "erro: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "erro: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new BufferedReader ( new InputStreamReader(conn.getInputStream()) );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Servidor diz: "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "erro: " + ioex.getMessage(), ioex);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.d(" UploadMSG","onPost");
pDialog.dismiss();
messageText.setText("Uploaded");
}
}
/********************END OF UPLOAD*************************************/
这是我的php文件
// Where the file is going to be placed
$target_path = "uploads/";
/* Add the original filename to our target path.
Result is "/uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['upfile']['name']);
if( $_FILES['upfile'] )
{
if(move_uploaded_file($_FILES['upfile']['tmp_name'], $target_path)) {
// $qry = "UPDATE users set image=".$target_path." where username='$username'";
// $db->query($qry);
echo "O arquivo ". basename( $_FILES['upfile']['name']).
" está sendo enviado";
} else{
echo "Ocorreu um erro ao realizar envio de arquivo, por favor tente novamente!\n";
echo "Nome do arquivo: " . basename( $_FILES['upfile']['name'])."\n";
echo "target_path: " .$target_path;
}
}else
{
echo "Nenhum arquivo careregado!";
/*** ever enters here!!! ***/
}
你能帮助我吗?
谢谢!!!
答案 0 :(得分:1)
代码看起来很好但是在你的AsyncTask doInBackground方法中,更改 String lineEnd =&#34;&#34;; 到 String lineEnd =&#34; \ r \ n&#34 ;; 应该工作。反斜杠确保r,n不被解释为字母而是解释为特殊字符,r-返回滑架和n-新线。
答案 1 :(得分:0)
我有同样的问题。我描述了它here。在我的情况下,问题是当我尝试发送内容类型为“multipart / form-data”的文件时。我没有解决它,也许它处理PHP或服务器,但问题仍然没有答案。
作为临时解决方案,我将请求类型更改为默认帖子类型(application / x-www-form-urlencoded),并将图像转换为base64字符串。也许它会有所帮助。
答案 2 :(得分:0)
我刚遇到同样的问题。使用200响应发布文件成功,但_FILES为空。我通过指定Content-Length标头来解决问题。 E.g:
conn.setRequestProperty("Content-Length", Integer.toString(fileInputStream.available()));
编辑:因此,当使用它时,该文件出现在_FILES中,但错误代码为3.但是,我也调用了conn.setChunkedStreamingMode(1024);.删除Content-Length并调用setChunkedStreamingMode对我有用,但我很确定空的_FILES与Content-Length字段没有正确设置有关。