drvpv7995 2016-03-24 10:46 采纳率: 100%
浏览 70

图像上传为多部分到服务器文件夹在android中不起作用

Uploading image to server folder from android gallery is not working. It does not any exception and the image is not uploaded to the folder. Googled all the sample examples and tried many solutions but nothing works for me.

package net.simplifiedcoding.volleyupload;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UploadImageDemo extends Activity {

TextView tv;
Button b;
int serverResponseCode = 0;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    b = (Button)findViewById(R.id.but);
    tv = (TextView)findViewById(R.id.tv);
    tv.setText("Uploading file path :- '/storage/sdcard0/DCIM/Camera/IMG_20160112_104150.jpg'");

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(UploadImageDemo.this, "", "Uploading file...", true);
            new Thread(new Runnable() {
                public void run() {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            tv.setText("uploading started.....");
                        }
                    });
                    int response= uploadFile("/storage/sdcard0/DCIM/Camera/IMG_20160112_104150.jpg");

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

public int uploadFile(String sourceFileUri) {
    String upLoadServerUri = "http://appsinbox.com/appstimesheetnew/testup.php";
    String fileName = sourceFileUri;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "
";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        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);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        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();
        final String serverResponseMessage = conn.getResponseMessage();

        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        if(serverResponseCode == 200){
            runOnUiThread(new Runnable() {
                public void run() {
                    tv.setText("File Upload Completed.");

                }
            });
        }

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

    } catch (MalformedURLException ex) {
        dialog.dismiss();
        ex.printStackTrace();

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

    }
    dialog.dismiss();
    return serverResponseCode;
}
}

And php code is below

$target_path1 = "/var/www/vhosts/logineduhub.com/appsinbox/appstimesheetnew/uploads/";
/* Add the original filename to our target path. Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename($_FILES['uploaded_file']['name']);
if( chmod($target_path1, 0777) ) {
// more code
chmod($target_path1, 0755);

if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1))
    {
        echo "hi";
    echo "The first file " . basename($_FILES['uploaded_file']['name']) . " has been uploaded.";
}
else {
    echo "bye";
    echo "There was an  error uploading the file, please try again!";
    echo "filename: " . basename($_FILES['uploaded_file']['name']);
    echo "target_path: " . $target_path1;
}


}
else
{
echo "Couldn't do it.";
}
  • 写回答

1条回答 默认 最新

  • doutu3352 2016-03-24 11:01
    关注

    This is how i did it (more or less :))

    Android:

    public String uploadFile(String u, String imageFilePath, String filename) {
    
        String attachmentName = "image";
        String attachmentFileName = filename + ".jpg";
        String crlf = "
    ";
        String twoHyphens = "--";
        String boundary = "*****";
    
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
    
        StringBuffer response = new StringBuffer();
    
        try {
            FileInputStream fileInputStream = new FileInputStream(imageFilePath);
    
            try {
    
                HttpURLConnection httpUrlConnection = null;
                URL url = new URL(u);
                httpUrlConnection = (HttpURLConnection) url.openConnection();
                httpUrlConnection.setUseCaches(false);
                httpUrlConnection.setDoOutput(true);                
    
                httpUrlConnection.setRequestMethod("POST");
                httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
                httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
                httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
    
                DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream());
    
                request.writeBytes(twoHyphens + boundary + crlf);
                request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
                request.writeBytes(crlf);
    
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    
                while (bytesRead > 0) {
                    request.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
    
                request.writeBytes(crlf);
                request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
    
                request.flush();
                request.close();
    
                int responseCode = httpUrlConnection.getResponseCode();
    
                String inputLine = "";
    
                if (responseCode == 200) {
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(httpUrlConnection.getInputStream()));
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                }
    
            } catch (MalformedInputException e) {
                Log.v("Err", e.getMessage());
            } catch (ConnectException e) {
                Log.v("Err", e.getMessage());
            } catch (UnknownHostException e) {
                Log.v("Err", e.getMessage());
            } catch (Exception e) {
                Log.v("Err", e.getMessage());
            }
    
        } catch (FileNotFoundException e) {
            Log.v("Err", e.getMessage());
        }
    
        return response.toString();
    
    }
    

    and php

    <?php
    
        define('DS',DIRECTORY_SEPARATOR);       
    
        $response = 0;
    
        if($_FILES){        
            if(!$_FILES['image']['error']){
                if(is_uploaded_file($_FILES['image']['tmp_name'])){                 
    
                    $dirpath = 'path to save file';
    
                    if(!is_dir($dirpath)){
                        mkdir($dirpath,0777);
                    }
    
                    $destination = $dirpath.DS.$_FILES['image']['name'];
                    if(move_uploaded_file($_FILES['image']['tmp_name'], $destination)){
                        $response = 1;
                    }
                }
            }
        }
    
        echo $response;
    
     ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源