2016-12-15 3 views
1

사용자가 파일을 첨부하여 서버 (Java Servlet)로 보낼 수있는 양식이 포함 된 웹 페이지 (JSP & AngularJS)를 만들었습니다. 그러면 서버는 해당 파일을 가져 와서 HTTP POST 요청에 첨부하여 API로 전달합니다.FileItem을 HTTP POST 요청에 연결하는 방법은 무엇입니까?

JSP 파일 및 AngularJS 컨트롤러 내에있는 코드가 제대로 작동하는 것 같습니다. 파일이 웹 페이지에서 서버로 보내지면 Java 서블릿에서 파일 세부 정보 (필드 이름과 크기는 같지만 내용 유형이나 파일 이름은 아님)에 액세스하여 System.out.println()을 통해 인쇄 할 수 있습니다.

제가 지금 직면하고있는 문제는 HttpPost (postRequest)에 FileItem (첨부 파일)을 첨부하는 방법을 찾는 것입니다.

파일을 업로드하는 방법에 대한 온라인 예제를 많이 읽었지만이 예제에서는 파일이 다른 위치로 전달되는 대신 서버의 디스크에 저장된다고 가정합니다. 이건 내 현재 코드는 (문제가 자바 서블릿 섹션 것 같다)

입니다 :

JSP 파일 :

<form name="issueForm"> 
    <input id="attachment" class="form-control" type="file" data-ng-model="attachment"/> 
    <button type="submit" data-ng-click="setAttachment()">Create Issue</button> 
</form> 

AngularJS와 컨트롤러 :

app.directive('fileModel', ['$parse', function ($parse) { 
    return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      var model = $parse(attrs.fileModel); 
      var modelSetter = model.assign; 

      element.bind('change', function() { 
       scope.$apply(function() { 
        modelSetter(scope, element[0].files[0]); 
       }); 
      }); 
     } 
    }; 
}]); 

$scope.setAttachment = function() 
{ 
    var attachment = $scope.attachment; 
    var fd = new FormData(); 
    fd.append('attachment', attachment); 

    $http({ 
     url: 'IssueAttachment', 
     method: 'POST', 
     transformRequest: function(data, headersGetterFunction) { return data; }, 
     headers: { 'Content-Type': undefined }, 
     data: fd 
    }) 
    .success(function(data, status) { alert("Success: " + status); }) 
    .error(function(data, status) { alert("Error: " + status); }); 
} 

자바 서블릿 :

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 
FileItem attachment = null; 
boolean isMultipart = ServletFileUpload.isMultipartContent(request); 

if (!isMultipart) { System.out.println("Not Multipart Content!"); } 
else { 
    FileItemFactory factory = new DiskFileItemFactory(); 
    ServletFileUpload upload = new ServletFileUpload(factory); 
    List items = null; 
    try { 
     items = upload.parseRequest(new ServletRequestContext(request)); 
    } catch (FileUploadException e) { e.printStackTrace(); } 
    try { 
     //Get attachment and print details 
     //This section prints "attachment", 9, null, null in that order). 
     attachment = (FileItem) items.get(0); 
     System.out.println("Field Name: " + attachment.getFieldName()); 
     System.out.println("Size: " + attachment.getSize()); 
     System.out.println("Content Type: " + attachment.getContentType()); 
     System.out.println("File Name: " + attachment.getName()); 
    } catch (Exception e) { e.printStackTrace(); } 

    //Create a HTTP POST and send the attachment. 
    HttpClient httpClient = HttpClientBuilder.create().build(); 
    HttpPost postRequest = new HttpPost(API_URL); 
    MultipartEntityBuilder entity = MultipartEntityBuilder.create(); 
    entity.addPart("attachment", new FileBody(attachment)); //THE ERROR OCCURS HERE. 
    postRequest.setEntity(entity.build()); 
    try { 
     HttpResponse response = httpClient.execute(postRequest); 
    } catch (IOException e) { e.printStackTrace(); } 
} 
} 
+0

* // 오류가 여기 OCCURS * ** 케어 공유 ** –

+0

*하지만 콘텐츠 형식 또는 파일 이름 * ** 어쩌면이.? ** –

+0

** 첨부 파일 ** 변수가 파일 유형이라면'entity.addPart ("attachment", new FileBody (attachment));'줄이 실행되지만 대신 FileItem이됩니다. 이클립스는 오류가 발생하여 밑줄을 긋는다. 디스크에 저장하지 않고 전달할 때 파일 형식을 사용할 수 없습니다. – dat3450

답변

1

를 사용하여 종료 다음

FileItem file = (FileItem)items.get(0); 
//Create a temporary file. 
File myFile = File.createTempFile(base, extension); 
//Write contents to temporary file. 
file.write(myFile); 

/** 
* Do whatever you want with the temporary file here... 
*/ 

//Delete the temporary file. 
myFile.delete(); //-OR- myFile.deleteOnExit(); 
관련 문제