2011-11-25 3 views
-1

가능한 중복 :
How to upload a file using Java HttpClient library working with PHP - strange problemjava를 사용하여 이미지 파일과 함께 양식을 제출하는 방법은 무엇입니까?

나는 자동으로 두 개의 필드와 함께 웹 사이트에 양식을 제출할 수있는 스크립트를 만들려고 해요 : 제목과 설명과 파일 입력 I을 이미지를 업로드해야합니다. 마지막 날에 내가 구글에서 발견 된 모든 페이지를 검색 한하지만 난 내 문제 ... 나는 또한 쿠키를 게시 할 필요가 를 해결할 수없는, 내가 사용 쿠키했습니다 :

connection.setRequestProperty("Cookie", cookie); //this worked 

을하지만, 내가 먼저 I'we이 HttpURLConnection의를 사용하여 시도 양식을 제출 문제가 있지만 지금은 사용하여 내 문제를 해결하기 위해 노력하고있어, 그것을 알아낼 수 없습니다 HttpClient를
HTML 양식은 다음과 같습니다

<form action="submit.php" method="post" enctype="multipart/form-data"> 
<input type="text" name="title"> 
<input name="biguploadimage" type="file"> 
<textarea name="description"></textarea> 
<input type="image" src="/images/submit-button.png"> 
</form> 

내 이미지는 d:/images/x.gif 에 있습니다. 내가 자바를 처음 사용하기 때문에 완전한 코드를 제공한다. O를 사용하고 HttpClient를 사용하여 쿠키를 만드는 방법은 무엇입니까? 조언을 많이 주셔서 감사합니다!

+2

JAVA 나 PHP를 사용하고 싶습니까? 귀하의 HTML 양식을 PHP로 제출하기 때문에 ... – GEMI

+0

자바를 사용하여 양식을 제출하고 싶습니다. – coolboycsaba

+0

html 양식이 내 웹 사이트에 없기 때문에 매일 적어도 한두 번 양식을 제출해야하므로 양식을 작성하여 자동으로 제출하는 스크립트를 만들고 싶습니다. – coolboycsaba

답변

0

볼 수 있었다 나는 최근에했던이 사용하는 스프링 웹 MVC와 아파치 코 몬즈는 FileUpload :

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

import org.apache.commons.fileupload.*; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.io.FilenameUtils; 
import org.apache.commons.lang.StringUtils; 
import org.apache.log4j.Logger; 

(...) 

    @RequestMapping(method = RequestMethod.POST) 
    public ModelAndView uploadFile(HttpServletRequest request, HttpServletResponse response) { 

     ModelAndView modelAndView = new ModelAndView("view"); 

     if (ServletFileUpload.isMultipartContent(request)) { 
      handleMultiPartContent(request); 
     } 

     return modelAndView; 
    } 


    private void handleMultiPartContent(HttpServletRequest request) { 

     ServletFileUpload upload = new ServletFileUpload(); 
     upload.setFileSizeMax(2097152); // 2 Mb 
     try { 
      FileItemIterator iter = upload.getItemIterator(request); 
      while (iter.hasNext()) { 
       FileItemStream item = iter.next(); 
       if (!item.isFormField()) { 
        File tempFile = saveFile(item); 
        // process the file 
       } 
      } 
     } 
     catch (FileUploadException e) { 
      LOG.debug("Error uploading file", e); 
     } 
     catch (IOException e) { 
      LOG.debug("Error uploading file", e); 
     } 
    } 

    private File saveFile(FileItemStream item) { 

     InputStream in = null; 
     OutputStream out = null; 
     try { 
      in = item.openStream(); 
      File tmpFile = File.createTempFile("tmp_upload", null); 
      tmpFile.deleteOnExit(); 
      out = new FileOutputStream(tmpFile); 
      long bytes = 0; 
      byte[] buf = new byte[1024]; 
      int len; 
      while ((len = in.read(buf)) > 0) { 
       out.write(buf, 0, len); 
       bytes += len; 
      } 
      LOG.debug(String.format("Saved %s bytes to %s ", bytes, tmpFile.getCanonicalPath())); 
      return tmpFile; 
     } 
     catch (IOException e) { 

      LOG.debug("Could not save file", e); 
      Throwable cause = e.getCause(); 
      if (cause instanceof FileSizeLimitExceededException) { 
       LOG.debug("File too large", e); 
      } 
      else { 
       LOG.debug("Technical error", e); 
      } 
      return null; 
     } 
     finally { 
      try { 
       if (in != null) { 
        in.close(); 
       } 
       if (out != null) { 
        out.close(); 
       } 
      } 
      catch (IOException e) { 
       LOG.debug("Could not close stream", e); 
      } 
     } 
    } 

이 임시 파일에 업로드 된 파일을 저장합니다. 당신은 업로드를 통해 모든 낮은 수준의 제어를 필요로하지 않는 경우

, CommonsMultipartResolver를 사용하는 것이 훨씬 간단합니다 :

<!-- Configure the multipart resolver --> 
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    <property name="maxUploadSize" value="2097152"/> 
</bean> 

는 JSP의 예 양식 :

<form:form modelAttribute="myForm" method="post" enctype="multipart/form-data"> 
    <form:input path="bean.uploadedFile" type="file"/> 
</form> 

bean의 uploadedDocument는 org.springframework.web.multipart.CommonsMultipartFile 타입이며 컨트롤러에서 direcly에 접근 할 수있다. (multipartResolver는 모든 multipart 요청을 자동으로 분석한다)

관련 문제