2014-07-22 23 views
6

Tôi mới sử dụng API REST. Tôi muốn tải tệp người dùng đã chọn lên đường dẫn do người dùng cung cấp (đường dẫn từ xa hoặc đường dẫn cục bộ) bằng cách sử dụng REST API. Tệp html của tôi có 1 hộp văn bản và 1 trình chọn tệp. Người dùng sẽ nhập FilePath (vị trí thư mục máy địa phương hoặc từ xa) vào hộp văn bản. Vui lòng đề xuất cách giải quyết vấn đề này.Tải lên tệp bằng API Rest trong Java

Đây là mã của tôi:

FileUpload.html::

<body> 
    <form action="rest/file/upload" method="post" enctype="multipart/form-data"> 
     <p> 
      Select a file : <input type="file" name="file" size="45" /> 
     </p> 
     <p>Target Upload Path : <input type="text" name="path" /></p> 
     <input type="submit" value="Upload It" /> 
    </form> 
</body> 

UploadFileService.java

@Path("/file") 
public class UploadFileService { 

    @POST 
    @Path("/upload") 
    @Consumes(MediaType.MULTIPART_FORM_DATA) 
    public Response uploadFile(
      @FormDataParam("file") InputStream uploadedInputStream, 
      @FormDataParam("file") FormDataContentDisposition fileDetail, 
      @FormParam("path") String path) { 

     /*String uploadedFileLocation = "d://uploaded/"                 + fileDetail.getFileName();*/ 

     /*String uploadedFileLocation = //10.217.14.88/Installables/uploaded/"                 + fileDetail.getFileName();*/ 
     String uploadedFileLocation = path 
       + fileDetail.getFileName(); 

     // save it 
     writeToFile(uploadedInputStream, uploadedFileLocation); 

     String output = "File uploaded to : " + uploadedFileLocation; 

     return Response.status(200).entity(output).build(); 

    } 

    // save uploaded file to new location 
    private void writeToFile(InputStream uploadedInputStream, 
      String uploadedFileLocation) { 

     try { 
      OutputStream out = new FileOutputStream(new File(
        uploadedFileLocation)); 
      int read = 0; 
      byte[] bytes = new byte[1024]; 

      out = new FileOutputStream(new File(uploadedFileLocation)); 
      while ((read = uploadedInputStream.read(bytes)) != -1) { 
       out.write(bytes, 0, read); 
      } 
      out.flush(); 
      out.close(); 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 

    } 

} 

web.xml

<display-name>JAXRSFileUploadJerseyExample</display-name> 
<servlet> 
    <servlet-name>jersey-serlvet</servlet-name> 
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> 
    <init-param> 
     <param-name>com.sun.jersey.config.property.packages</param-name> 
     <param-value>com.mkyong.rest</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

<servlet-mapping> 
    <servlet-name>jersey-serlvet</servlet-name> 
    <url-pattern>/rest/*</url-pattern> 
</servlet-mapping> 

Ngoại lệ:

HTTP Status 500 - com.sun.jersey.api.container.ContainerException: Exception obtaining parameters 
type Exception report 
message com.sun.jersey.api.container.ContainerException: Exception obtaining parameters 
description The server encountered an internal error that prevented it from fulfilling this request. 
exception 
javax.servlet.ServletException: com.sun.jersey.api.container.ContainerException: Exception obtaining parameters 
     com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:425) 
     com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) 
     com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) 
     javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 
root cause 
com.sun.jersey.api.container.ContainerException: Exception obtaining parameters 
     com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:54) 
     com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125) 
     com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153) 
     com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203) 
     com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) 
     com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288) 
     com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) 
     com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) 
     com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) 
     com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) 
     com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469) 
     com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400) 
     com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) 
     com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) 
     com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) 
     com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) 
     com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) 
     javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 
root cause 
java.lang.IllegalStateException: The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded 
     com.sun.jersey.server.impl.model.parameter.FormParamInjectableProvider$FormParamInjectable.getValue(FormParamInjectableProvider.java:81) 
     com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46) 
     com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125) 
     com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153) 
     com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203) 
     com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) 
     com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288) 
     com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) 
     com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) 
     com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) 
     com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) 
     com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469) 
     com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400) 
     com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) 
     com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) 
     com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) 
     com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) 
     com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) 
     javax.servlet.http.HttpServlet.service(HttpServlet.java:728) 

Trả lời

8

Tôi đã cập nhật chữ ký của phương thức trong lớp dưới đây và làm việc tốt của nó. Thay vì @FormParam, sử dụng @FormDataParam("path") Đường dẫn chuỗi và giải quyết được sự cố của tôi. Dưới đây là mã Cập nhật:

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 

import javax.ws.rs.Consumes; 
import javax.ws.rs.FormParam; 
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response; 

import com.sun.jersey.core.header.FormDataContentDisposition; 
import com.sun.jersey.multipart.FormDataParam; 

@Path("/file") 
public class UploadFileService { 

@POST 
@Path("/upload") 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
public Response uploadFile(
     @FormDataParam("file") InputStream uploadedInputStream, 
     @FormDataParam("file") FormDataContentDisposition fileDetail, 
     @FormDataParam("path") String path) { 


    // Path format //10.217.14.97/Installables/uploaded/ 
    System.out.println("path::"+path); 
    String uploadedFileLocation = path 
      + fileDetail.getFileName(); 

    // save it 
    writeToFile(uploadedInputStream, uploadedFileLocation); 

    String output = "File uploaded to : " + uploadedFileLocation; 

    return Response.status(200).entity(output).build(); 

} 

// save uploaded file to new location 
private void writeToFile(InputStream uploadedInputStream, 
     String uploadedFileLocation) { 

    try { 
     OutputStream out = new FileOutputStream(new File(
       uploadedFileLocation)); 
     int read = 0; 
     byte[] bytes = new byte[1024]; 

     out = new FileOutputStream(new File(uploadedFileLocation)); 
     while ((read = uploadedInputStream.read(bytes)) != -1) { 
      out.write(bytes, 0, read); 
     } 
     out.flush(); 
     out.close(); 
    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

    } 

    } 
+0

mã java có chấp nhận bất kỳ loại tệp nào và lưu nó ở vị trí đã xác định không ?? Tôi muốn lưu định dạng tập tin như .pdf, .doc, .jpg –

+0

nếu mã trên có vấn đề với lọ sử dụng này nhập khẩu maven: com.sun.jersey jersey-server 1,8 com.sun.jersey.contribs jersey-nhiều phần dữ liệu 1,8

1

Một giải pháp khả thi

@Consumes chú thích và đặt nó là dòng ứng dụng octet. Sử dụng phương pháp http PUT. Sau đó, trong ứng dụng khách, đọc byte từ tệp và tải lên.

mẫu mã của tôi cho một dịch vụ REST để nén một tập tin là ở đây - https://stackoverflow.com/a/32253028/15789

Hope this helps.

Các vấn đề liên quan