gpt4 book ai didi

java - 使用POST数据用java将png上传到服务器

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:11 26 4
gpt4 key购买 nike

嗨,我在尝试使用 java 和 php 将 png 图像传输到我的网络服务器时遇到了一些麻烦,我尝试过使用 FTP,但是我编写的脚本软件阻止了端口 21,使其变得无用

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

也许只是对正在发生的事情的解释可能会有所帮助,以便我能够掌握我到底想用 java 和 php 做什么

任何帮助将不胜感激!

最佳答案

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

下面是一个将带有文件的 POST 请求发送到特定 URL 的方法:

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 !");
}
}

为了完成上传,您必须有一个处理该 POST 请求的 php 代码,这是:

<?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并且可以非常简单地从字符串构建。该文件也可以从表示其路径的字符串构建。

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

关于java - 使用POST数据用java将png上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17841577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com