PHP文件上载后文件已损坏

时间:2017-04-04 10:40:30

标签: php android file-upload

通过我的Android应用程序上传到本地主机的所有文件都已损坏。

,文件大小低于原始文件,因此无法打开文件。

这是我的Android文件上传

 public class FileHandler {
String response;
DataOutputStream dataOutputStream;
public String  uploadFile(String requestURL, final String selectedFilePath , HashMap<String, Object> postDataParams){

    int serverResponseCode = 0;

    HttpURLConnection connection;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";


    int bytesRead,bytesAvailable,bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File selectedFile = new File(selectedFilePath);

        try{
            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL(requestURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file",selectedFilePath);

            //creating new dataoutputstream
            dataOutputStream = new DataOutputStream(connection.getOutputStream());

            //writing bytes to data outputstream
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + selectedFilePath + "\"" + lineEnd);


            //returns no. of bytes present in fileInputStream
            bytesAvailable = fileInputStream.available();
            //selecting the buffer size as minimum of available bytes or 1 MB
            bufferSize = Math.min(bytesAvailable,maxBufferSize);
            //setting the buffer as byte array of size of bufferSize
            buffer = new byte[bufferSize];

            //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
            bytesRead = fileInputStream.read(buffer,0,bufferSize);

            //loop repeats till bytesRead = -1, i.e., no bytes are left to read
            while (bytesRead > 0){
                //write the bytes read from inputstream
                dataOutputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }
            dataOutputStream.writeBytes(lineEnd);

            // Upload POST Data
            Iterator<String> keys = postDataParams.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = postDataParams.get(key).toString();

                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
                dataOutputStream.writeBytes("Content-Type: text/plain" + lineEnd);
                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(value);
                dataOutputStream.writeBytes(lineEnd);
            }
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


            serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

            //response code of 200 indicates the server status OK
            if (serverResponseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line="";
                while((line = br.readLine()) != null) {
                    response =  line;
                }
                System.out.println(response);
                //  response = br.readLine();

            }
            else {
                response="Error" + serverResponseCode;
            }

            //closing the input and output streams
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();



        } catch (FileNotFoundException e) {
            e.printStackTrace();


        } catch (MalformedURLException e) {
            e.printStackTrace();


        } catch (IOException e) {
            e.printStackTrace();
        }

            return response;
}

和我的PHP代码:

<?php


require_once('dbconnect.php');


$appName = $_POST['appName'];
$acctID = $_POST['acctID'];

$file_path = "../app_file/";
$filename = basename($_FILES['uploaded_file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);

    $newFilePath = $file_path . $acctID . '_' . $appName . '_' . 'file.' . $extension;
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $newFilePath)) {
        echo "10";
    } else{
        echo $newFilePath;
    }
?>

我无法找到解决问题的方法。我的Android应用程序没有错误。文件上传没有问题。

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。我添加了

    private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}