上传文件到服务器与Android [英] Uploading file to server with android

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

问题描述

我一直在一个应用程序在Android上,应该抓住从SD卡的图像,然后将其上传到我的服务器。我能得到事先知情同意用这个作为URI的例子给了 HTTP上传到服务器: //www.androidexample.com/media/Uplo​​adToServer.php 。但是,图像将无法上传到我的本地服务器我使用URI 192.1xx.x.xxx/使用来自无线本地主机从Android设备uploadtoserver.php,我收到一个serverresponse 200和确定。

我用Google搜索的答案,并研究了3天,不能得到这个工作。

我的code:

Java的一部分:

 公共类UploadToServer延伸活动{

TextView中的MessageText;
按钮uploadButton;
INT serverResponse code = 0;
ProgressDialog对话框= NULL;

字符串upLoadServerUri = NULL;

/**********  文件路径 *************/
字符串路径= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)的ToString();

最后弦乐uploadFilePath =路径+/ MyApp的/温度/;
最后弦乐uploadFileName =temp.png;

@覆盖
公共无效的onCreate(包savedInstanceState){

    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_upload_to_server);

    uploadButton =(按钮)findViewById(R.id.uploadButton);
    =的MessageText(TextView中)findViewById(R.id.messageText);

    messageText.setText(上传文件路径: - 到/ mnt / SD卡/+ uploadFileName +');

    / ************* PHP脚本路径**************** /
    upLoadServerUri =htt​​p://192.168.1.144/Uplo​​adToServer.php;

    uploadButton.setOnClickListener(新OnClickListener(){
        @覆盖
        公共无效的onClick(视图v){

            对话框= ProgressDialog.show(UploadToServer.this,,上传文件...,真正的);

            新主题(新的Runnable(){
                    公共无效的run(){
                         runOnUiThread(新的Runnable(){
                                公共无效的run(){
                                    messageText.setText(上传开始......);
                                }
                            });

                         uploadFile(uploadFilePath ++ uploadFileName);

                    }
                  })。开始();
            }
        });
}

公众诠释uploadFile(字符串sourceFileUri){


      字符串文件名= sourceFileUri;

      HttpURLConnection的康恩= NULL;
      DataOutputStream类DOS = NULL;
      字符串lineEnd =\ r \ N的;
      串twoHyphens = - ;
      字符串边界=*****;
      INT读取动作,方bytesAvailable,缓冲区大小;
      byte []的缓冲区;
      INT maxBufferSize = 1 * 1024 * 1024;
      文件的SourceFile =新的文件(sourceFileUri);

      如果(!sourceFile.isFile()){

           dialog.dismiss();

           Log.e(一个UploadFile,源文件不存在
                               + uploadFilePath ++ uploadFileName);

           runOnUiThread(新的Runnable(){
               公共无效的run(){
                   messageText.setText(源文件不存在
                           + uploadFilePath ++ uploadFileName);
               }
           });

           返回0;

      }
      其他
      {
           尝试 {

                 //打开一个URL连接到这个Servlet
               的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);
               网址URL =新的URL(upLoadServerUri);

               //打开一个HTTP连接网址
               康恩=(HttpURLConnection类)url.openConnection();
               conn.setDoInput(真正的); //允许输入
               conn.setDoOutput(真正的); //允许输出
               conn.setUseCaches(假); //不要使用缓存副本
               conn.setRequestMethod(POST);
               conn.setRequestProperty(连接,保持活动);
               conn.setRequestProperty(ENCTYPE,多部分/表单数据);
               conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
               conn.setRequestProperty(uploaded_file,文件名);

               DOS =新DataOutputStream类(conn.getOutputStream());

               dos.writeBytes(twoHyphens +边界+ lineEnd);
               dos.writeBytes(内容处置:表格数据;名称= \uploaded_file \;文件名= \
                                         +文件名+\+ lineEnd);

               dos.writeBytes(lineEnd);

               //创建最大大小的缓冲区
               方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);

               从服务器//回应(code和消息)
               serverResponse code = conn.getResponse code();
               串serverResponseMessage = conn.getResponseMessage();

               Log.i(一个UploadFile,HTTP响应是:
                       + serverResponseMessage +:+ serverResponse code);

               如果(serverResponse code == 200){

                   runOnUiThread(新的Runnable(){
                        公共无效的run(){

                            弦乐味精=文件上传已完成\ñ\ñ看到这里上传的文件:\ñ\ N
                                          +http://192.168.1.144/Uplo​​adToServer.php/
                                          + uploadFileName;

                            messageText.setText(MSG);
                            Toast.makeText(UploadToServer.this,文件上传完成。,
                                         Toast.LENGTH_SHORT).show();
                        }
                    });
               }

               //关闭流//
               fileInputStream.close();
               dos.flush();
               dos.close();

          }赶上(MalformedURLException的前){

              dialog.dismiss();
              ex.printStackTrace();

              runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      messageText.setText(MalformedURLException的例外情况:检查脚本的网址。);
                      Toast.makeText(UploadToServer.this,MalformedURLException的,
                                                          Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e(上传文件到服务器,错误:+ ex.getMessage(),前);
          }赶上(例外五){

              dialog.dismiss();
              e.printStackTrace();

              runOnUiThread(新的Runnable(){
                  公共无效的run(){
                      messageText.setText(GOT例外:看logcat的);
                      Toast.makeText(UploadToServer.this,得到了异常:看logcat的,
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e(上传文件到服务器异常,异常
                                               + e.getMessage(),E);
          }
          dialog.dismiss();
          返回serverResponse code;

       } //结束else块
     }
 

}

由于它工作在一台服务器上,我相信这是一个服务器端的问题

PHP部分

 < PHP
 $ target_path1 =无功/网络/图片/
 $ target_path1 = $ target_path1。基本名($ _ FILES ['uploaded_file'] ['名称']);
 如果(move_uploaded_file($ _ FILES ['uploaded_file'] ['tmp_name的值'],$ target_path1)){
回声成功;
} 其他{
 回声失败;}
 ?>
 

解决方案

 < PHP
    $ target_path1 =/无功/网络/图片/
    $ target_path1 = $ target_path1。基本名($ _ FILES ['uploaded_file'] ['名称']);
    如果(move_uploaded_file($ _ FILES ['uploaded_file'] ['tmp_name的值'],$ target_path1)){
        回声成功;
    } 其他 {
        回声不及格;
    }
 ?>
 

它看起来就像你引用一个相对目录:无功/网络/图片/ ,如果你的PHP文件是 /无功/网络/ 来开始将指向 /无功/网络/无功/网络/图片/ 我怀疑是你打算。

只要修改 $ target_path1 使它成为绝对路径 /无功/网络/图片/

I have been working on an app on android that should grab an image from the sd card and then upload it to my server. I was able to get the pic to upload to a server using this as the uri the example gave "http://www.androidexample.com/media/UploadToServer.php. However the image will not upload to my localhost server i am using the local host from a wifi from an android device using URI 192.1xx.x.xxx/uploadtoserver.php. I recieve a serverresponse 200 and OK.

I have googled for answers and researched for 3 days and cannot get this to work.

My Code:

Java part:

public class UploadToServer extends Activity {

TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;

String upLoadServerUri = null;

/**********  File Path *************/
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();

final String uploadFilePath = path + "/MyApp/Temp/";
final String uploadFileName = "temp.png";

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload_to_server);

    uploadButton = (Button)findViewById(R.id.uploadButton);
    messageText  = (TextView)findViewById(R.id.messageText);

    messageText.setText("Uploading file path :- '/mnt/sdcard/"+uploadFileName+"'");

    /************* Php script path ****************/
    upLoadServerUri = "http://192.168.1.144/UploadToServer.php";

    uploadButton.setOnClickListener(new OnClickListener() {            
        @Override
        public void onClick(View v) {

            dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);

            new Thread(new Runnable() {
                    public void run() {
                         runOnUiThread(new Runnable() {
                                public void run() {
                                    messageText.setText("uploading started.....");
                                }
                            });                      

                         uploadFile(uploadFilePath + "" + uploadFileName);

                    }
                  }).start();        
            }
        });
}

public int uploadFile(String sourceFileUri) {


      String fileName = sourceFileUri;

      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(sourceFileUri); 

      if (!sourceFile.isFile()) {

           dialog.dismiss(); 

           Log.e("uploadFile", "Source File not exist :"
                               +uploadFilePath + "" + uploadFileName);

           runOnUiThread(new Runnable() {
               public void run() {
                   messageText.setText("Source File not exist :"
                           +uploadFilePath + "" + uploadFileName);
               }
           }); 

           return 0;

      }
      else
      {
           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", 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);   

                }

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

               if(serverResponseCode == 200){

                   runOnUiThread(new Runnable() {
                        public void run() {

                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                          +" http://192.168.1.144/UploadToServer.php/"
                                          +uploadFileName;

                            messageText.setText(msg);
                            Toast.makeText(UploadToServer.this, "File Upload Complete.", 
                                         Toast.LENGTH_SHORT).show();
                        }
                    });                
               }    

               //close the streams //
               fileInputStream.close();
               dos.flush();
               dos.close();

          } catch (MalformedURLException ex) {

              dialog.dismiss();  
              ex.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("MalformedURLException Exception : check script url.");
                      Toast.makeText(UploadToServer.this, "MalformedURLException", 
                                                          Toast.LENGTH_SHORT).show();
                  }
              });

              Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
          } catch (Exception e) {

              dialog.dismiss();  
              e.printStackTrace();

              runOnUiThread(new Runnable() {
                  public void run() {
                      messageText.setText("Got Exception : see logcat ");
                      Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", 
                              Toast.LENGTH_SHORT).show();
                  }
              });
              Log.e("Upload file to server Exception", "Exception : "
                                               + e.getMessage(), e);  
          }
          dialog.dismiss();       
          return serverResponseCode; 

       } // End else block 
     } 

}

Since it works on one server i believe this is a server-side issue

PHP part

<?php
 $target_path1 = "var/www/images/"
 $target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
 if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
echo "Success";
} else{
 echo "fail";}
 ?>

解决方案

 <?php
    $target_path1 = "/var/www/images/"
    $target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) { 
        echo "Success";
    } else {
        echo "fail";
    }
 ?>

It looks like you were referencing a relative directory: var/www/images/ which, if your php file was in /var/www/ to begin with would be pointing to /var/www/var/www/images/ which I doubt is what you were intending.

Just change $target_path1 to make it an absolute path /var/www/images/

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

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