2009-08-21 14 views
5

साथ पीएचपी पेज मैं एक फ़ाइल अपलोड और php पेज में पोस्ट करने के लिए कोई तरीका होना चाहिए करने के लिए फ़ाइल ...अपलोड करें और पोस्ट जावा

मेरे php पृष्ठ है:

<?php 
$maxsize = 10485760; 
$array_estensioni_ammesse=array('.tmp'); 
$uploaddir = 'uploads/'; 
if (is_uploaded_file($_FILES['file']['tmp_name'])) 
{ 
    if($_FILES['file']['size'] <= $maxsize) 
    { 
     $estensione = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], "."), strlen($_FILES['file']['name'])-strrpos($_FILES['file']['name'], "."))); 
     if(!in_array($estensione, $array_estensioni_ammesse)) 
     { 
      echo "File is not valid!\n"; 
     } 
     else 
     { 
      $uploadfile = $uploaddir . basename($_FILES['file']['name']); 
      echo "File ". $_FILES['file']['name'] ." uploaded successfully.\n"; 
      if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) 
      { 
       echo "File is valid, and was successfully moved.\n"; 
      } 
      else 
       print_r($_FILES); 
     } 
    } 
    else 
     echo "File is not valid!\n"; 
} 
else 
{ 
    echo "Upload Failed!!!"; 
    print_r($_FILES); 
} 
?> 

और मैं इस जावा का उपयोग मेरे डेस्कटॉप एप्लिकेशन में कोड:

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection(); 
     httpUrlConnection.setDoOutput(true); 
     httpUrlConnection.setRequestMethod("POST"); 
     OutputStream os = httpUrlConnection.getOutputStream(); 
     Thread.sleep(1000); 
     BufferedInputStream fis = new BufferedInputStream(new FileInputStream("tmpfile.tmp")); 

     for (int i = 0; i < totalByte; i++) { 
      os.write(fis.read()); 
      byteTrasferred = i + 1; 
     } 

     os.close(); 
     BufferedReader in = new BufferedReader(
       new InputStreamReader(
       httpUrlConnection.getInputStream())); 

     String s = null; 
     while ((s = in.readLine()) != null) { 
      System.out.println(s); 
     } 
     in.close(); 
     fis.close(); 

लेकिन मुझे हमेशा "अपलोड विफल हुआ !!!" संदेश।

+0

@Albe यह नहीं मिल सकता है परिवर्तनीय 'कुलबाइट' और 'बाइट ट्रांस्फर'। उन चर के मूल्य क्या हैं? – alexandre1985

उत्तर

0

आप सही HTML फ़ाइल अपलोड semantics का उपयोग नहीं कर रहे हैं। आप सिर्फ यूआरएल में डेटा का एक गुच्छा पोस्ट कर रहे हैं।

  • आप के रूप में है जावा कोड रख सकते हैं, और php कोड बदलने सिर्फ एक फ़ाइल के रूप में कच्चे पोस्ट को पढ़ने के लिए:

    आप 2 विकल्प यहाँ है।

  • एक वास्तविक फ़ाइल अपलोड करने के लिए जावा कोड को संभवतः common library का उपयोग करके अपलोड करें।

मैं जावा कोड को मानकों के अनुरूप तरीके से करने की सिफारिश करता हूं।

+0

धन्यवाद लेकिन मैं बाहरी पुस्तकालयों का उपयोग नहीं करना चाहता ... मैं फ़ाइल के रूप में कच्चे POST को पढ़ने के लिए PHP कोड कैसे बदल सकता हूं? –

+0

ऐसा करने के लिए, आपको नीचे सॉकेट उदाहरण का उपयोग करना होगा। चेतावनी दी जानी चाहिए, यह एक बहुत सी अतिरिक्त कोड होने जा रहा है और शायद डीबगिंग करने में काफी समय लगेगा। गंभीर रूप से बाहरी पुस्तकालयों के प्रति अपने विचलन पर विचार करें। (मैं समझता हूं कि कभी-कभी आपके हाथ बंधे होते हैं, बस महसूस करें कि यह बहुत आसान होगा) –

+0

लेकिन फ़ाइल (या डेटा) अपलोड करने का एक आसान तरीका मौजूद नहीं है? –

4

आपको PHP के लिए एक फॉर्म-मल्टीपार्ट एन्कोडेड पोस्ट का उपयोग करने की आवश्यकता है ताकि आप जिस तरीके से प्रयास कर रहे हैं उसे पढ़ने में सक्षम हो सकें। This वेबसाइट इसे करने का एक अच्छा तरीका बताती है और पुस्तकालयों के लिंक हैं जो आपकी मदद कर सकते हैं।

3

सभी उपरोक्त उत्तरों 100% सही हैं।

 // Compose the request header 
     StringBuffer buf = new StringBuffer(); 
     buf.append("POST "); 
     buf.append(uploader.getUploadAction()); 
     buf.append(" HTTP/1.1\r\n"); 
     buf.append("Content-Type: multipart/form-data; boundary="); 
     buf.append(boundary); 
     buf.append("\r\n"); 
     buf.append("Host: "); 
     buf.append(uploader.getUploadHost()); 
     buf.append(':'); 
     buf.append(uploader.getUploadPort()); 
     buf.append("\r\n"); 
     buf.append("Connection: close\r\n"); 
     buf.append("Cache-Control: no-cache\r\n"); 

     // Add cookies 
     List cookies = uploader.getCookies(); 
     if (!cookies.isEmpty()) 
      { 
       buf.append("Cookie: "); 
       for (Iterator iterator = cookies.iterator(); iterator.hasNext();) 
        { 
         Parameter parameter = (Parameter)iterator.next(); 

         buf.append(parameter.getName()); 
         buf.append('='); 
         buf.append(parameter.getValue()); 

         if (iterator.hasNext()) 
          buf.append("; "); 
        } 

       buf.append("\r\n"); 
      } 

     buf.append("Content-Length: "); 

     // Request body 
     StringBuffer body = new StringBuffer(); 
     List fields = uploader.getFields(); 
     for (Iterator iterator = fields.iterator(); iterator.hasNext();) 
      { 

       Parameter parameter = (Parameter) iterator.next(); 

       body.append("--"); 
       body.append(boundary); 
       body.append("\r\n"); 
       body.append("Content-Disposition: form-data; name=\""); 
       body.append(parameter.getName()); 
       body.append("\"\r\n\r\n"); 
       body.append(parameter.getValue()); 
       body.append("\r\n"); 
      } 

     body.append("--"); 
     body.append(boundary); 
     body.append("\r\n"); 
     body.append("Content-Disposition: form-data; name=\""); 
     body.append(uploader.getImageFieldName()); 
     body.append("\"; filename=\""); 
     body.append(file.getName()); 
     body.append("\"\r\n"); 
     body.append("Content-Type: image/pjpeg\r\n\r\n"); 

     String boundary = "WHATEVERYOURDEARHEARTDESIRES"; 
     String lastBoundary = "\r\n--" + boundary + "--\r\n"; 
     long length = file.length() + (long) lastBoundary.length() + (long) body.length(); 
     long total = buf.length() + body.length(); 

     buf.append(length); 
     buf.append("\r\n\r\n"); 

     // Upload here 
     InetAddress address = InetAddress.getByName(uploader.getUploadHost()); 
     Socket socket = new Socket(address, uploader.getUploadPort()); 
     try 
      { 
       socket.setSoTimeout(60 * 1000); 
       uploadStarted(length); 

       PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream())); 
       out.print(buf); 
       out.print(body); 

       // Send the file 
       byte[] bytes = new byte[1024 * 65]; 
       int size; 
       InputStream in = new BufferedInputStream(new FileInputStream(file)); 
       try 
        { 
         while ((size = in.read(bytes)) > 0) 
          { 
           total += size; 
           out.write(bytes, 0, size); 
           transferred(total); 
          } 
        } 
       finally 
        { 
         in.close(); 
        } 

       out.print(lastBoundary); 
       out.flush(); 

       // Read the response 
       BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
       while (reader.readLine() != null); 
      } 
     finally 
      { 
       socket.close(); 
      } 
+0

लेकिन फ़ाइल (या डेटा) अपलोड करने का एक आसान तरीका मौजूद नहीं है? –

+0

जितना आसान हो जाता है उतना आसान है। कुछ और पुस्तकालयों का उपयोग कर रहा है। – Daniil

+0

यदि मैं एक टेक्स्ट फ़ाइल भेजना चाहता हूं तो यह परिवर्तनीय 'अपलोडर' – alexandre1985

0

मुझे पता है यह थोड़ा पुराना है, लेकिन मैं सिर्फ एक answer to a similar question है जो लागू यहाँ भी होना चाहिए पोस्ट: तुम भी सादा सॉकेट, जिस स्थिति में अपने विधि इस प्रकार दिखाई देगा का उपयोग कर सकते हैं। इसमें डेनिल के समान कोड शामिल है, लेकिन सॉकेट के बजाय HttpURLConnection का उपयोग करता है।

11

यह एक पुरानी धागा है, लेकिन दूसरों के लाभ के लिए, यहाँ की एक पूरी तरह से काम कर रहा उदाहरण है कि वास्तव में क्या सेशन के लिए पूछता है:

पीएचपी सर्वर कोड:

<?php 

$target_path = "uploads/"; 

$target_path = $target_path . basename($_FILES['uploadedfile']['name']); 

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedfile']['name'])." has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 

?> 

जावा ग्राहक कोड:

import java.io.OutputStream; 
import java.io.InputStream; 
import java.net.URLConnection; 
import java.net.URL; 
import java.net.Socket; 

public class Main { 
    private final String CrLf = "\r\n"; 

    public static void main(String[] args) { 
     Main main = new Main(); 
     main.httpConn(); 
    } 

    private void httpConn() { 
     URLConnection conn = null; 
     OutputStream os = null; 
     InputStream is = null; 

     try { 
      URL url = new URL("http://localhost/test/post.php"); 
      System.out.println("url:" + url); 
      conn = url.openConnection(); 
      conn.setDoOutput(true); 

      String postData = ""; 

      InputStream imgIs = getClass().getResourceAsStream("/test.jpg"); 
      byte[] imgData = new byte[imgIs.available()]; 
      imgIs.read(imgData); 

      String message1 = ""; 
      message1 += "-----------------------------4664151417711" + CrLf; 
      message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"test.jpg\"" 
        + CrLf; 
      message1 += "Content-Type: image/jpeg" + CrLf; 
      message1 += CrLf; 

      // the image is sent between the messages in the multipart message. 

      String message2 = ""; 
      message2 += CrLf + "-----------------------------4664151417711--" 
        + CrLf; 

      conn.setRequestProperty("Content-Type", 
        "multipart/form-data; boundary=---------------------------4664151417711"); 
      // might not need to specify the content-length when sending chunked 
      // data. 
      conn.setRequestProperty("Content-Length", String.valueOf((message1 
        .length() + message2.length() + imgData.length))); 

      System.out.println("open os"); 
      os = conn.getOutputStream(); 

      System.out.println(message1); 
      os.write(message1.getBytes()); 

      // SEND THE IMAGE 
      int index = 0; 
      int size = 1024; 
      do { 
       System.out.println("write:" + index); 
       if ((index + size) > imgData.length) { 
        size = imgData.length - index; 
       } 
       os.write(imgData, index, size); 
       index += size; 
      } while (index < imgData.length); 
      System.out.println("written:" + index); 

      System.out.println(message2); 
      os.write(message2.getBytes()); 
      os.flush(); 

      System.out.println("open is"); 
      is = conn.getInputStream(); 

      char buff = 512; 
      int len; 
      byte[] data = new byte[buff]; 
      do { 
       System.out.println("READ"); 
       len = is.read(data); 

       if (len > 0) { 
        System.out.println(new String(data, 0, len)); 
       } 
      } while (len > 0); 

      System.out.println("DONE"); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      System.out.println("Close connection"); 
      try { 
       os.close(); 
      } catch (Exception e) { 
      } 
      try { 
       is.close(); 
      } catch (Exception e) { 
      } 
      try { 

      } catch (Exception e) { 
      } 
     } 
    } 
} 

आप पता लगा सकते हैं कि कैसे अपनी साइट के लिए यह अनुकूल करने के लिए, लेकिन मैं इसके बाद के संस्करण कोड का परीक्षण किया है और यह काम करता है। मैं इसके लिए क्रेडिट नहीं ले सकता है, हालांकि >>See Original Post

+0

@CSchulz नहीं ढूंढ सकता है, मुझे "सामग्री-प्रकार: छवि/जेपीईजी" क्या बदलना चाहिए? – alexandre1985

+0

"टेक्स्ट/सादा" काम करेगा यदि आपके पास यूएस ASCII है, यदि आपको एक और वर्णमाला की आवश्यकता है तो आपको इसे निर्दिष्ट करने की आवश्यकता है। – CSchulz

+0

विंडोज 7 के साथ संगतता के लिए 'इनपुटस्ट्रीम imgIs = getClass()। GetResourceAsStream ("/ test.jpg"); '' FileInputStream imgIs = new fileInputStream (नई फ़ाइल ("test.jpg") के साथ' ' – alexandre1985

17

हालांकि धागा बहुत पुरानी है, वहां अभी भी चारों ओर किसी को इस समस्या को हल करने के लिए एक और अधिक आसान तरीका (मेरे जैसे :))

की तलाश में हो सकता है कुछ शोध के बाद मुझे मूल पोस्टर के जावा-कोड को बदले बिना फ़ाइल को ऊपर उठाने का एक तरीका मिला। तुम बस निम्नलिखित पीएचपी-कोड का उपयोग करने के लिए है:

<?php 
    $filename="abc.xyz"; 
    $fileData=file_get_contents('php://input'); 
    $fhandle=fopen($filename, 'wb'); 
    fwrite($fhandle, $fileData); 
    fclose($fhandle); 
    echo("Done uploading"); 
?> 

इस कोड को सिर्फ जावा आवेदन द्वारा भेजे गए कच्चे डेटा प्राप्त करने में है और यह एक फ़ाइल में लिख रहे हैं। हालांकि, एक समस्या है: आपको मूल फ़ाइल नाम नहीं मिलता है, इसलिए आपको इसे किसी और तरह से प्रेषित करना होगा।

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php?filename=abc.def").openConnection(); 

को

HttpURLConnection httpUrlConnection = (HttpURLConnection)new URL("http://www.mypage.org/upload.php").openConnection(); 

परिवर्तन अपने PHP स्क्रिप्ट आप बदलना में:

मैं एक Get-पैरामीटर, जो जावा कोड में एक छोटे से बदलाव जरूरी बनाता का उपयोग कर इस समस्या का समाधान लाइन

$filename="abc.xyz"; 

करने के लिए
$filename=$_GET['filename']; 

यह समाधान किसी भी बाहरी librarys का उपयोग नहीं करता और मेरे पास बहुत अन्य तैनात लोगों में से कुछ की तुलना में अधिक सरल लगता है ...

आशा मैं मदद कर सकता है किसी को भी :)

+0

वाह !! ! यह सादगी की शक्ति है। निष्पक्ष, समझने में आसान, और मजबूत काम किया। –

+0

क्यों नहीं 'file_put_contents ($ filename, $ fileData); '? – Sandman4

संबंधित मुद्दे