Jersey File Upload Example文件上传案例

Add Jersey maven multipart dependency

To use multipart features you need to add jersey-media-multipart module to your pom.xml file:

<dependency>

    <groupId>org.glassfish.jersey.media</groupId>

    <artifactId>jersey-media-multipart</artifactId>

    <version>2.19</version>

</dependency>

Add MultiPartFeature in web.xml

Further, you are required to add MultiPartFeature in Jersey configuration to let it know that you will use multipart requests. Simplest way is to add support through web.xml file.

<servlet>

    <servlet-name>jersey-serlvet</servlet-name>

    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

    <init-param>

        <param-name>jersey.config.server.provider.packages</param-name>

        <param-value>com.howtodoinjava.jersey</param-value>

    </init-param>

    <init-param>

        <param-name>jersey.config.server.provider.classnames</param-name>

        <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>

    </init-param>

    <load-on-startup>1</load-on-startup>

</servlet>

Writing Upload REST API

Now look at actual REST API for file upload, which will receive and save the file.

@POST

@Path("/pdf")

@Consumes({MediaType.MULTIPART_FORM_DATA})

public Response uploadPdfFile(  @FormDataParam("file") InputStream fileInputStream,

                                @FormDataParam("file") FormDataContentDisposition fileMetaData)throws Exception

{

    String UPLOAD_PATH = "c:/temp/";

    try

    {

        int read = 0;

        byte[] bytes = new byte[1024];

 

        OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName()));

        while ((read = fileInputStream.read(bytes)) != -1)

        {

            out.write(bytes, 0, read);

        }

        out.flush();

        out.close();

    catch (IOException e)

    {

        throw new WebApplicationException("Error while uploading file. Please try again !!");

    }

    return Response.ok("Data uploaded successfully !!").build();

}

Test file upload using HTML Form

Simply create a file ‘fileUpload.html‘ file in ‘webapp‘ folder and paste this code.

<html>

    <body>

        <h1>File Upload Example - howtodoinjava.com</h1>

     

        <form action="rest/upload/pdf" method="post" enctype="multipart/form-data">

     

            <p>Select a file : <input type="file" name="file" size="45" accept=".pdf" /></p>

            <input type="submit" value="Upload PDF" />

             

        </form>

     

    </body>

</html>

Now hit the URL : “http://localhost:8080/JerseyDemos/fileUpload.html” and it will display a HTML file control to browse the file. Select any PDF file and click on “Upload PDF” button.

Your file will be uploaded and you will get the message: “Data uploaded successfully !!”

Test file upload using java client

If you are looking for uploading files using java clients then you can modify below working code as per your need.

public static void main(String[] args) throws IOException

{

    final Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();

 

    final FileDataBodyPart filePart = new FileDataBodyPart("file"newFile("C:/temp/sample.pdf"));

    FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

    final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo","bar").bodyPart(filePart);

      

    final WebTarget target = client.target("http://localhost:8080/JerseyDemos/rest/upload/pdf");

    final Response response = target.request().post(Entity.entity(multipart, multipart.getMediaType()));

     

    //Use response object to verify upload success

     

    formDataMultiPart.close();

    multipart.close();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值