从Android的上传图片到PHP服务器 [英] Upload a picture from Android to PHP server

查看:168
本文介绍了从Android的上传图片到PHP服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想文件从我的Andr​​oid设备上传到PHP服务器。有螺纹同样的问题,但他是用不同的方法。我的Andr​​oid端code工作正常,并没有显示错误消息,但服务器无法接收任何文件。这里是我的示例code,我发现它在网上。

 进口java.io.FileInputStream中;
进口android.app.Activity;
进口android.os.Bundle;
进口java.io.DataInputStream中;
进口java.io.DataOutputStream中;
进口的java.io.File;
进口java.io.IOException异常;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口android.util.Log;

公共类uploadfile延伸活动{
/ **第一次创建活动时调用。 * /
@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    doFileUpload();
}

私人无效doFileUpload(){
HttpURLConnection的康恩= NULL;
DataOutputStream类DOS = NULL;
inStream中的DataInputStream = NULL;
字符串exsistingFileName =/sdcard/def.jpg;

//这是这个地方是你做错了什么。
字符串lineEnd =RN;
串twoHyphens = - ;
字符串边界=*****;

INT读取动作,方bytesAvailable,缓冲区大小;
byte []的缓冲区;
INT maxBufferSize = 1 * 1024 * 1024;
字符串responseFromServer =;
字符串urlString =htt​​p://192.168.1.6/index.php;

尝试
    {
        // ------------------客户端请求
        Log.e(MediaPlayer的,内部第二种方法);
        的FileInputStream的FileInputStream =新的FileInputStream(新文件(exsistingFileName));

                                        //打开一个URL连接到这个Servlet
                                        网址URL =新的URL(urlString);

                                        //打开一个HTTP连接网址
                                        康恩=(HttpURLConnection类)url.openConnection();

                                        //允许输入
                                        conn.setDoInput(真正的);

                                        //允许输出
                                        conn.setDoOutput(真正的);

                                        //不要使用缓存副本。
                                        conn.setUseCaches(假);

                                        //使用POST方法。
                                        conn.setRequestMethod(POST);
                                        conn.setRequestProperty(连接,保持活动);
                                        conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);

                                        DOS =新DataOutputStream类(conn.getOutputStream());
                                        dos.writeBytes(twoHyphens +边界+ lineEnd);
                                        dos.writeBytes(内容处置:表格数据;名称= \UploadedFile的\;文件名= \
                                                            + exsistingFileName +\+ lineEnd);
                                        dos.writeBytes(lineEnd);
                                        Log.e(MediaPlayer的,头信息);

                                        //创建最大大小的缓冲区
                                        方bytesAvailable = fileInputStream.available();
                                        BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                                        缓冲区=新的字节[BUFFERSIZE]

                                        //读取文件,并将其写入形式...
                                        读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);

                                        而(读取动作大于0){
                                                                dos.write(缓冲液,0,BUFFERSIZE);
                                                                方bytesAvailable = fileInputStream.available();
                                                                BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                                                                读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
                                        }

                                        //发送多部分表格数据文件数据后necesssary ...
                                        dos.writeBytes(lineEnd);
                                        dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);

                                        //关闭流
                                        Log.e(MediaPlayer的,文件写入);
                                        fileInputStream.close();
                                        dos.flush();
                                        dos.close();

                    }

      赶上(MalformedURLException的前)

     {

           Log.e(MediaPlayer的,错误:+ ex.getMessage(),前);

      }



      赶上(IOException异常IOE)

      {

           Log.e(MediaPlayer的,错误:+ ioe.getMessage(),IOE);

      }

      // ------------------读取服务器响应
      尝试 {
            inStream中=新的DataInputStream(conn.getInputStream());
            字符串str;

            而((海峡= inStream.readLine())!= NULL)
            {
                 Log.e(MediaPlayer的,服务器响应+ STR);
            }

            inStream.close();
      }

      赶上(IOException异常ioex){
           Log.e(MediaPlayer的,错误:+ ioex.getMessage(),ioex);
      }

    }
    }
 

和我的PHP服务器端code如下:

 < PHP

 $ target_path =上传/;

 $ target_path = $ target_path。基本名($ _ FILES ['UploadedFile的'] ['名称']);

 如果(move_uploaded_file($ _ FILES ['UploadedFile的'] ['tmp_name的值'],$ target_path)){
回声文件。基本名($ _ FILES ['UploadedFile的'] ['名称'])。
    已上载;
 }

 其他{
      回声发生错误上传文件,请重试!;
   }
   ?>
 

Apache正在运行。当我运行的服务器,这个错误味精似乎有一个错误上载文件,请重试!我在日食检查日志数据,我认为是插座的问题,但我不知道。请帮助,如果有人知道的解决方案。

  5月11号至28号:37:55.310:DEBUG / SntpClient(59):请求时失败:产生java.net.SocketException:地址族不支持的协议
 

解决方案

看来,服务器不响应到客户端。尝试使用通过Android应用程序的FTP连接上传,如果工作再检查接受连接和可写目录的Apache配置。当我有一个类似的问题,事实证明,我的目录没有给写权限。

是从Java或Apache的错误?

I am trying to upload file to a php server from my android device. There is thread with same question but he is using a different method. My Android side code works fine and shows no error message but server is not receiving any file. here is my sample code, I found it online.

import java.io.FileInputStream;
import android.app.Activity;
import android.os.Bundle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;

public class uploadfile extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    doFileUpload();
}

private void doFileUpload(){
HttpURLConnection conn =    null;
DataOutputStream dos = null;
DataInputStream inStream = null;    
String exsistingFileName = "/sdcard/def.jpg";

// Is this the place are you doing something wrong.
String lineEnd = "rn";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://192.168.1.6/index.php";

try
    {
        //------------------ CLIENT REQUEST 
        Log.e("MediaPlayer","Inside second Method");
        FileInputStream fileInputStream = new FileInputStream(new    File(exsistingFileName) );

                                        // 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("Content-Type", "multipart/form-data;boundary="+boundary);

                                        dos = new DataOutputStream( conn.getOutputStream() );
                                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                                                            + exsistingFileName + "\"" + lineEnd);
                                        dos.writeBytes(lineEnd);
                                        Log.e("MediaPlayer","Headers are written");

                                        // 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);

                                        // close streams
                                        Log.e("MediaPlayer","File is written");
                                        fileInputStream.close();
                                        dos.flush();
                                        dos.close();

                    }

      catch (MalformedURLException ex)

     {

           Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);

      }



      catch (IOException ioe)

      {

           Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);

      }

      //------------------ read the SERVER RESPONSE
      try {
            inStream = new DataInputStream ( conn.getInputStream() );
            String str;

            while (( str = inStream.readLine()) != null)
            {
                 Log.e("MediaPlayer","Server Response"+str);
            }

            inStream.close();
      }

      catch (IOException ioex){
           Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
      }

    }
    }

and my php server side code is as follows

<?php

 $target_path = "uploads/";

 $target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

 if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
 } 

 else{
      echo "There was an error uploading the file, please try again!";
   }
   ?>

Apache is running. When i run server, this error msg appears There was an error uploading the file, please try again!. I have checked the log data in eclipse and what i think is the socket problem but i am not sure. Please help if anyone knows the solution.

11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol

解决方案

It seems that the server is not responding to the client. Try uploading using an ftp connection through the Android application, if that works then check your Apache configuration on accepting connections and the writable directories. When I had a similar problem it turned out that my directory gave no write privileges.

Is the error from Java or from Apache?

这篇关于从Android的上传图片到PHP服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆