簡體   English   中英

使用POST數據使用Java將png上載到服務器

[英]uploading png to server with java using POST data

您好,嘗試使用java和php將png圖像傳輸到我的網絡服務器時遇到了一些麻煩,我嘗試使用FTP進行了嘗試,但是Im腳本編寫的軟件阻止了端口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,並且可以非常簡單地從String進行構建。 也可以從代表其路徑的字符串構建文件。

我沒有花時間對它進行正確的測試,但是它是建立在正確的工作解決方案之上的,因此希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM