【问题标题】:uploading png to server with java using POST data使用 POST 数据使用 java 将 png 上传到服务器
【发布时间】:2013-07-24 09:00:51
【问题描述】:

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

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

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

任何帮助将不胜感激!

【问题讨论】:

    标签: java php upload png html-post


    【解决方案1】:

    不久前我也遇到过同样的问题。 经过一番研究,我发现来自 Apache (http://hc.apache.org/) 的 HttpComponents 库包含了几乎所有您需要以非常简单的方式构建 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,并且可以非常简单地从字符串构建。该文件也可以从表示其路径的字符串构建。

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

    【讨论】:

    • 非常感谢,这真的帮助了我更多地研究它并做一些测试!我只有一个问题 request.addPart("file", fileB); 行中的 fileB 是什么?
    • 哦,对不起,我在我的代码中删除了错误的行(实际上在我使用的原始代码中,POST 请求包含另一个字段:“name”,因为我想输入一个我的数据库的其他名称而不是真实文件名)。我应该删除 StringBody 并保留 FileBody 但我做了相反的事情,我将对其进行编辑。
    • ahhhhh 我现在明白了,这更有意义:)
    猜你喜欢
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 2015-10-05
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多