2014-01-22 2 views
-1
내가 JAX-RS와 REST API를 사용하고

,서버 측에서 실제로 업로드 된 파일을 어떻게 얻을 수 있습니까?

난 그냥 파일을 업로드하고 다음과 같이 내 서버 코드는,

@POST 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
@Produces(MediaType.TEXT_PLAIN) 
@Path("/upload") 
public String uploadFunction(@Context UriInfo uriInfo, 
     @FormDataParam("upload") final InputStream inputStream, 
     @FormDataParam("upload") final FormDataContentDisposition fileDetail) { 
//Here I want to get the actual file. For eg: If i upload a myFile.txt. I need to get it as myFile.txt here 
} 

내가 사용하여 파일의 내용을 구문 분석 할 때 내 코드가 제대로 작동 일부 작업을 수행했습니다. 이제 정확한 파일을 원해. 실제 파일이 첨부 된 메일을 보내야하므로

여기 실제 파일을 가져오고 싶습니다. 예 : myFile.txt를 업로드하는 경우. 여기 myfile.txt로 가져와야합니다. 그것을 어떻게 성취 할 수 있습니까?

+0

왜 두 번'PARAM을 upload' 지정 않습니다

그래서이 경우 당신은 다음과 같은 일을 할 수있을 것인가? –

+0

Lutz Horn :이 업로드 작업을 위해 클라이언트 측에서 이름을 "업로드"로 설정했기 때문에. 내 업데이트 된 질문을 참조하십시오 – Prince

+0

입력 스트림이 있고 파일 이름을 검색 할 수 있습니다. 이 외에 정확히 무엇이 필요합니까? –

답변

2

내가 틀릴 수도 있지만 파일이 아직 서버에 저장되어 있지 않기 때문에 InputStream을 사용할 때만 입력 스트림을 얻을 수 있습니다.

private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/somepath/tmp/uploaded_files/"; 

@POST 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
@Produces(MediaType.TEXT_PLAIN) 
@Path("/upload") 
public String uploadFunction(@Context UriInfo uriInfo, 
     @FormDataParam("upload") final InputStream inputStream, 
     @FormDataParam("upload") final FormDataContentDisposition fileDetail) { 

     String filePath = SERVER_UPLOAD_LOCATION_FOLDER + fileDetail.getFileName(); 
     // save the file to the server 
     saveFile(inputStream, filePath); 
     String output = "File saved to server location : " + filePath; 
     return Response.status(200).entity(output).build(); 
} 

private void saveFile(InputStream uploadedInputStream, String serverLocation) { 
    try { 
     OutputStream outputStream = new FileOutputStream(new File(serverLocation)); 
     int read = 0; 
     byte[] bytes = new byte[1024]; 
     outputStream = new FileOutputStream(new File(serverLocation)); 
     while ((read = uploadedInputStream.read(bytes)) != -1) { 
      outputStream.write(bytes, 0, read); 
     } 
     outputStream.flush(); 
     outputStream.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
관련 문제