RESTful JAX-RS檔案上傳範例


與上一篇教學中講解的檔案下載一樣,JAX-RS也可以實現上傳檔案,上傳的檔案型別可以是:影象檔案,PDF檔案,Excel檔案,文字檔案等。

  • @FormDataParam("file")注釋用於提及服務類中的file引數。
  • @Consumes(MediaType.MULTIPART_FORM_DATA)用於提供檔案上載的資訊。

要使用JAX-RS API上傳檔案,我們將使用jersey 來實現。首先開啟Eclipse,建立一個動態Web專案:JAXRSFileUpload,結構如下所示 -

要通過jersey實現上傳檔案,需要在web.xml 檔案中提供額外的組態項。如下所示 -

<init-param>  
    <param-name>jersey.config.server.provider.classnames</param-name>  
    <param-value>org.glassfish.jersey.filter.LoggingFilter;  
     org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>  
</init-param>

讓我們看看使用RESTful JAX-RS API上傳檔案的完整程式碼。

JAX-RS檔案上傳

檔案:FileUploadService.java -

package com.yiibai.rest;

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import javax.ws.rs.Consumes;  
import javax.ws.rs.POST;  
import javax.ws.rs.Path;  
import javax.ws.rs.core.MediaType;  
import javax.ws.rs.core.Response;  
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;  
import org.glassfish.jersey.media.multipart.FormDataParam;  
@Path("/files")  
public class FileUploadService {  
    @POST  
    @Path("/upload")  
    @Consumes(MediaType.MULTIPART_FORM_DATA)  
    public Response uploadFile(  
            @FormDataParam("file") InputStream uploadedInputStream,  
            @FormDataParam("file") FormDataContentDisposition fileDetail) { 
            String filename = fileDetail.getFileName();
            String files[] = filename.split(":");
            filename = files[files.length-1];
            System.out.println("filename => "+ filename);
            String fileLocation = "D:\" + filename;  
            System.out.println("filename => "+ fileLocation);
                    //saving file  
            try {  
                FileOutputStream out = new FileOutputStream(new File(fileLocation));  
                int read = 0;  
                byte[] bytes = new byte[1024];  
                out = new FileOutputStream(new File(fileLocation));  
                while ((read = uploadedInputStream.read(bytes)) != -1) {  
                    out.write(bytes, 0, read);  
                }  
                out.flush();  
                out.close();  
            } catch (IOException e) {e.printStackTrace();}  
            String output = "File successfully uploaded to : " + fileLocation;  
            return Response.status(200).entity(output).build();  
        }  
  }

檔案: web.xml -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <servlet>
        <servlet-name>Jersey REST Service</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.yiibai.rest</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>org.glassfish.jersey.filter.LoggingFilter;  
     org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

檔案: index.html -

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JAXRS檔案上傳範例</title>
</head>
<body>
<h2>JAXRS檔案上傳範例</h2>  
<form action="rest/files/upload" method="post" enctype="multipart/form-data">  
       <p>  
        選擇檔案 : <input type="file" name="file" size="45" />  
       </p>  
       <input type="submit" value="提交上傳" />  
</form> 
</body>
</html>

現在在伺服器上執行此應用程式,您將看到以下輸出:

選擇一個要上傳的檔案,然後提交上傳,得到以下結果 -