使用POST数据将png上传到带有java的服务器


uploading png to server with java using POST data

嗨,我在尝试使用java和php将png图像传输到我的Web服务器时遇到了一些问题。我尝试过使用FTP,但我为其编写脚本的软件阻止了端口21,使其成为无用的

我被指示使用表单url编码的数据,然后使用POST请求来获取它我完全迷失在这个话题上,只能使用一些方向显然文件和图像托管网站使用相同的方法将文件和图像从用户的计算机传输到他们的服务器。

也许仅仅解释一下发生了什么可能会有所帮助,这样我就可以准确地掌握我试图用java和php做什么

任何帮助都将不胜感激!

我不久前也遇到过同样的问题。经过一些研究,我发现Apache的HttpComponents库(http://hc.apache.org/)包含了以一种非常简单的方式构建HTTP-POST请求所需的几乎所有内容。

以下是一种方法,它将向某个URL发送带有文件的POST请求:

public static void upload(URL url, File file) throws IOException, URISyntaxException {
    HttpClient client = new DefaultHttpClient(); //The client object which will do the upload
    HttpPost httpPost = new HttpPost(url.toURI()); //The POST request to send
    FileBody fileB = new FileBody(file);
    MultipartEntity request = new MultipartEntity(); //The HTTP entity which will holds the different body parts, here the file
    request.addPart("file", fileB);
    httpPost.setEntity(request);
    HttpResponse response = client.execute(httpPost); //Once the upload is complete (successful or not), the client will return a response given by the server
    if(response.getStatusLine().getStatusCode()==200) { //If the code contained in this response equals 200, then the upload is successful (and ready to be processed by the php code)
        System.out.println("Upload successful !");
    }
}

为了完成上传,您必须有一个php代码来处理POST请求,在这里:

<?php
$directory = 'Set here the directory you want the file to be uploaded to';
$filename = basename($_FILES['file']['name']);
if(strrchr($_FILES['file']['name'], '.')=='.png') {//Check if the actual file extension is PNG, otherwise this could lead to a big security breach
    if(move_uploaded_file($_FILES['file']['tmp_name'], $directory. $filename)) { //The file is transfered from its temp directory to the directory we want, and the function returns TRUE if successfull
        //Do what you want, SQL insert, logs, etc
    }
}
?>

提供给Java方法的URL对象必须指向php代码,如http://mysite.com/upload.php并且可以非常简单地从String构建。该文件也可以通过表示其路径的字符串来构建。

我没有花时间对它进行适当的测试,但它是建立在适当的工作解决方案之上的,所以我希望这将对您有所帮助。