Java HTTP Post Upload不是由PHP处理的

时间:2012-05-08 10:04:18

标签: java upload java-io http-request

我正在将带有HTTP Post请求的Java文件上传到我的upload.php文件中,但似乎PHP找不到临时文件。

这是我的Java代码:

    HttpURLConnection theUrlConnection = (HttpURLConnection) url.openConnection();
    theUrlConnection.setDoOutput(true);
    theUrlConnection.setDoInput(true);
    theUrlConnection.setUseCaches(false);
    theUrlConnection.setChunkedStreamingMode(1024);
    theUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
            + Boundary);

    DataOutputStream httpOut = new DataOutputStream(theUrlConnection.getOutputStream());


        String str = "--" + Boundary + "\r\n"
                   + "Content-Disposition: form-data;name=\"userfile\"; filename=\"" + f.getName() + "\"\r\n"
                   + "Content-Type: image/jpeg\r\n"
                   + "\r\n";

        httpOut.write(str.getBytes());



        FileInputStream uploadFileReader = new FileInputStream(f);
        int numBytesToRead = 1024;
        int availableBytesToRead;


        while ((availableBytesToRead = uploadFileReader.available()) > 0)
        {
            byte[] bufferBytesRead;
            bufferBytesRead = availableBytesToRead >= numBytesToRead ? new byte[numBytesToRead]
                    : new byte[availableBytesToRead];
            uploadFileReader.read(bufferBytesRead);
            httpOut.write(bufferBytesRead);
            httpOut.flush();
        }
        httpOut.write(("--" + Boundary + "--\r\n").getBytes());


    httpOut.flush();
    httpOut.close();

我的upload.php代码:

$content_dir = 'upload/'; 

$tmp_file = $_FILES['userfile']['tmp_name'];

if( !is_uploaded_file($tmp_file) )
{
    exit("Unable to find the file.");
}

$name_file = $_FILES['userfile']['name'];

if( !move_uploaded_file($tmp_file, $content_dir . $name_file) )
{
    exit("Unable to copy the file in ".$content_dir);
}

所以我用Java代码(name=\"userfile\")给文件命名为“userfile”,但PHP似乎找不到$_FILES['userfile'] ...

我使用Wireshark尝试调试,但一切似乎都正确(Content-Disposition: form-data;name="userfile"; filename="toupload.jpg"Unable to find the file.在答案中......

0 个答案:

没有答案