2013-09-03 21 views
14

webserviceにファイルを送信したいが、もっと情報を送る必要があるので、jsonで送信したい。しかし、私がjsonObjectの中にファイルを置くと、文字列ではないというエラーが出ます。私の質問は、私は私のファイルを取って文字列に変換してから、私のjsonの中に入れ、Webサービスでそれを取り出し、その文字列をファイルに変換する必要がありますか?それとも別の簡単な方法がありますか?ここでJSONObject内のファイルをREST WebServiceに送信

は私のコードです:

クライアント:すべての答えの後

private void send() throws JSONException{ 
    ClientConfig config = new DefaultClientConfig(); 
    Client client = Client.create(config); 
    client.addFilter(new LoggingFilter()); 
    WebResource service = client.resource("http://localhost:8080/proj/rest/file/upload_json"); 

    JSONObject my_data = new JSONObject(); 
    File file_upload = new File("C:/hi.txt"); 
    my_data.put("User", "Beth"); 
    my_data.put("Date", "22-07-2013"); 
    my_data.put("File", file_upload); 

    ClientResponse client_response = service.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, my_data); 

    System.out.println("Status: "+client_response.getStatus()); 

    client.destroy(); 
} 

WebServiceの

@POST 
@Path("/upload_json") 

@Consumes(MediaType.APPLICATION_JSON) 
@Produces("text/plain") 

public String receive(JSONObject json) throws JSONException { 

    //Here I'll save my file and make antoher things.. 
    return "ok"; 
} 

、ここに私のコードがある - みんなありがとう:

WebServiceの

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import javax.ws.rs.Consumes; 
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import org.codehaus.jettison.json.JSONException; 
import org.codehaus.jettison.json.JSONObject; 
import com.sun.jersey.core.util.Base64; 

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

    @POST 
    @Path("/upload_json") 

    @Consumes(MediaType.APPLICATION_JSON) 
    @Produces(MediaType.APPLICATION_JSON) 

    public JSONObject receiveJSON(JSONObject json) throws JSONException, IOException { 
     convertFile(json.getString("file"), json.getString("file_name")); 
     //Prints my json object 
     return json; 
    } 

    //Convert a Base64 string and create a file 
    private void convertFile(String file_string, String file_name) throws IOException{ 
     byte[] bytes = Base64.decode(file_string); 
     File file = new File("local_path/"+file_name); 
     FileOutputStream fop = new FileOutputStream(file); 
     fop.write(bytes); 
     fop.flush(); 
     fop.close(); 
    } 
} 

クライアント

import java.io.File; 
import java.io.IOException; 
import java.nio.file.Files; 
import javax.ws.rs.core.MediaType; 
import org.codehaus.jettison.json.JSONException; 
import org.codehaus.jettison.json.JSONObject; 
import com.sun.jersey.api.client.Client; 
import com.sun.jersey.api.client.ClientResponse; 
import com.sun.jersey.api.client.WebResource; 
import com.sun.jersey.api.client.config.ClientConfig; 
import com.sun.jersey.api.client.config.DefaultClientConfig; 
import com.sun.jersey.api.client.filter.LoggingFilter; 
import com.sun.jersey.core.util.Base64; 
import com.sun.jersey.multipart.FormDataMultiPart; 
import com.sun.jersey.multipart.file.FileDataBodyPart; 
import com.sun.jersey.multipart.impl.MultiPartWriter; 

public class MyClient { 


    public static void main(String[] args) throws JSONException, IOException 
    { 
     MyClient my_client = new MyClient(); 
     File file_upload = new File("local_file/file_name.pdf"); 
     my_client.sendFileJSON(file_upload); 
    } 


    private void sendFileJSON(File file_upload) throws JSONException, IOException{ 

     ClientConfig config = new DefaultClientConfig(); 
     Client client = Client.create(config); 
     client.addFilter(new LoggingFilter()); 
     WebResource service = client.resource("my_rest_address_path"); 
     JSONObject data_file = new JSONObject(); 
     data_file.put("file_name", file_upload.getName()); 
     data_file.put("description", "Something about my file...."); 
     data_file.put("file", convertFileToString(file_upload)); 

     ClientResponse client_response = service.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, data_file); 

     System.out.println("Status: "+client_response.getStatus()); 

     client.destroy(); 

    } 


    //Convert my file to a Base64 String 
    private String convertFileToString(File file) throws IOException{ 
     byte[] bytes = Files.readAllBytes(file.toPath()); 
     return new String(Base64.encode(bytes)); 
    } 

} 
+0

'dados'はどのようなタイプですか? –

+0

申し訳ありません...名前を変更するのを忘れましたが、dados = my_data – user2486187

+0

Base64.getDecoder().decode(file_string)の可能性がありますか? –

答えて

0

は私がMap<String, String>おそらく、dadosが参照しているかわからないが、私はあなたがちょうど

JSONObject my_data = new JSONObject(); 
File file_upload = new File("C:/hi.txt"); 
my_data.put("User", "Beth"); 
my_data.put("Date", "22-07-2013"); 
my_data.put("File", file_upload); 
を作成し JSONObjectを使用することにしたいと思います

しかし、これは役に立たず、あなたが思うことをしていない可能性があります。 Fileオブジェクトはファイルを保持しません。ファイルへのパスを保持します。 C:/hi.txt。これがJSONに入れた場合、それは生成されます

{"File" : "C:/hi.txt"} 

ファイルの内容は含まれません。

だから、あなたにもちょうどあなたがJSONでファイルアップロードをしようとしている場合、一つの方法は、Java 7のNIO

にファイルからバイトを読み取ることで、直接

JSONObject my_data = new JSONObject(); 
my_data.put("User", "Beth"); 
my_data.put("Date", "22-07-2013"); 
my_data.put("File", "C:/hi.txt"); 

ファイルパスを置くかもしれません

byte[] bytes = Files.readAllBytes(file_upload .toPath()); 

Base64は、これらのバイトをエンコードし、JSONObjectのStringとして書き込みます。 Apache Commonsを使用するコーデック

Base64.encodeBase64(bytes); 
my_data.put("File", new String(bytes)); 
+0

Commons Codecを使用する必要はありません。 'DatatypeConverter'は標準(JAXB)の一部です。 –

+0

ありがとう! Base64.encode(bytes)とBase64.decode(bytes)を持つcom.sun.jersey.core.util.Base64を使用しました。 – user2486187

-1

ファイルをバイト配列に変換してjson内で送信する必要があります。

以下を参照してください。send file to webservice

+0

私はこの解決策が複雑だと考えました...この解決策は他の解決策よりも優れていますか?私のファイルをバイトに変換してからBase64に文字列を変換してjsonに入れたので、Webサービスはその文字列を取り、Base64をバイトにデコードしてファイルを作成します。 – user2486187

+0

あなたがファイルを渡すために必要なことを既に発見した例です。 –

6

あなたは、例えば、Base64エンコードにファイルデータを変換し、それを転送する必要があります

byte[] bytes = Files.readAllBytes(file_upload.toPath()); 
dados.put("File", DatatypeConverter.printBase64Binary(bytes)); 
+2

いいえ。奇妙に見えますが、そうですが、バイト配列をBase64に変換する必要があります。 Base64 Stringをバイト配列に変換するには、 'parseBase64Binary(String)'を使用します。 –

+0

おかげさまで、Base64を使用する必要があることを知りました!私はBase64を使わずに作ろうとしましたが、pdfファイルに問題がありました。 – user2486187

+0

@MoritzPetersen、それは良いpraticeですか?私は良いアイデアは、JSONに埋め込まれた文字列としてファイルを送信しないと思う – well

2
@POST 
@Path("/uploadWeb") 
@Consumes(MediaType.MULTIPART_FORM_DATA) 
public Response uploadWeb( @FormDataMultiPart("image")  InputStream uploadedInputStream, 
       @FormDataParam("image")  FormDataContentDisposition fileDetail) { 

    int read = 0; 
    byte[] bytes = new byte[1024]; 
    while ((read = uploadedInputStream.read(bytes)) != -1) 
     System.out.write(bytes, 0, read); 
    return Response.status(HttpStatus.SC_OK).entity(c).build(); 
} 

とクライアント側(see this post)の:このよう

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
FileBody fileContent= new FileBody(new File(fileName)); 
StringBody comment = new StringBody("Filename: " + fileName); 
MultipartEntity reqEntity = new MultipartEntity(); 
reqEntity.addPart("file", fileContent); 
httppost.setEntity(reqEntity); 
HttpResponse response = httpclient.execute(httppost); 
HttpEntity resEntity = response.getEntity(); 
+0

どのように任意のJSONを変換するのですか? –

+0

それはファイルデータをアップロードする方法です、質問を読んで、彼はデータを送信したいが間違った方法を選択したい。 –

+0

なぜそれが間違っていますか?私は、json内で必要とするすべての情報をより簡単に送信することを考えました... – user2486187

1

私はそのに古いポストを知っているが、私はちょうど私が外部に依存を避けるために少しを追加しようと思いましたlibrarys。

//Convert my file to a Base64 String 
public static final String convertFileToString(File file) throws IOException{ 
    byte[] bytes = Files.readAllBytes(file.toPath()); 
    return new String(Base64.getEncoder().encode(bytes)); 
} 

//Convert a Base64 string and create a file 
public static final void convertFile(String file_string, String file_name) throws IOException{ 
    byte[] bytes = Base64.getDecoder().decode(file_string); 
    File file = new File("local_path/"+file_name); 
    FileOutputStream fop = new FileOutputStream(file); 
    fop.write(bytes); 
    fop.flush(); 
    fop.close(); 
} 
0

親切アドレスにあなたをIPローカルホストからマシンアドレスを変更 あなたのクライアントは以下のサービスを呼び出すために接続します。

**CLIENT TO CALL REST WEBSERVICE** 


    package in.india.client.downloadfiledemo; 

    import java.io.BufferedInputStream; 
    import java.io.File; 
    import java.io.FileInputStream; 
    import java.io.FileNotFoundException; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 

    import javax.ws.rs.core.MediaType; 
    import javax.ws.rs.core.Response.Status; 

    import com.sun.jersey.api.client.Client; 
    import com.sun.jersey.api.client.ClientHandlerException; 
    import com.sun.jersey.api.client.ClientResponse; 
    import com.sun.jersey.api.client.UniformInterfaceException; 
    import com.sun.jersey.api.client.WebResource; 
    import com.sun.jersey.multipart.BodyPart; 
    import com.sun.jersey.multipart.MultiPart; 

    public class DownloadFileClient { 

     private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile"; 

     public DownloadFileClient() { 

      try { 
       Client client = Client.create(); 
       WebResource objWebResource = client.resource(BASE_URI); 
       ClientResponse response = objWebResource.path("/") 
         .type(MediaType.TEXT_HTML).get(ClientResponse.class); 

       System.out.println("response : " + response); 
       if (response.getStatus() == Status.OK.getStatusCode() 
         && response.hasEntity()) { 
        MultiPart objMultiPart = response.getEntity(MultiPart.class); 
        java.util.List<BodyPart> listBodyPart = objMultiPart 
          .getBodyParts(); 
        BodyPart filenameBodyPart = listBodyPart.get(0); 
        BodyPart fileLengthBodyPart = listBodyPart.get(1); 
        BodyPart fileBodyPart = listBodyPart.get(2); 

        String filename = filenameBodyPart.getEntityAs(String.class); 
        String fileLength = fileLengthBodyPart 
          .getEntityAs(String.class); 
        File streamedFile = fileBodyPart.getEntityAs(File.class); 

        BufferedInputStream objBufferedInputStream = new BufferedInputStream(
          new FileInputStream(streamedFile)); 

        byte[] bytes = new byte[objBufferedInputStream.available()]; 

        objBufferedInputStream.read(bytes); 

        String outFileName = "D:/" 
          + filename; 
        System.out.println("File name is : " + filename 
          + " and length is : " + fileLength); 
        FileOutputStream objFileOutputStream = new FileOutputStream(
          outFileName); 
        objFileOutputStream.write(bytes); 
        objFileOutputStream.close(); 
        objBufferedInputStream.close(); 
        File receivedFile = new File(outFileName); 
        System.out.print("Is the file size is same? :\t"); 
        System.out.println(Long.parseLong(fileLength) == receivedFile 
          .length()); 
       } 
      } catch (UniformInterfaceException e) { 
       e.printStackTrace(); 
      } catch (ClientHandlerException e) { 
       e.printStackTrace(); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

     } 

     public static void main(String... args) { 
      new DownloadFileClient(); 
     } 

    } 


**SERVICE TO RESPONSE CLIENT** 

package in.india.service.downloadfiledemo; 

import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response; 

import com.sun.jersey.multipart.MultiPart; 

@Path("downloadfile") 
@Produces("multipart/mixed") 
public class DownloadFileResource { 

    @GET 
    public Response getFile() { 

     java.io.File objFile = new java.io.File(
       "D:/DanGilbert_2004-480p-en.mp4"); 
     MultiPart objMultiPart = new MultiPart(); 
     objMultiPart.type(new MediaType("multipart", "mixed")); 
     objMultiPart 
       .bodyPart(objFile.getName(), new MediaType("text", "plain")); 
     objMultiPart.bodyPart("" + objFile.length(), new MediaType("text", 
       "plain")); 
     objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed")); 

     return Response.ok(objMultiPart).build(); 

    } 

} 

**JAR NEEDED** 

jersey-bundle-1.14.jar 
jersey-multipart-1.14.jar 
mimepull.jar 

**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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
    id="WebApp_ID" version="2.5"> 
    <display-name>DownloadFileDemo</display-name> 
    <servlet> 
     <display-name>JAX-RS REST Servlet</display-name> 
     <servlet-name>JAX-RS REST Servlet</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>in.india.service.downloadfiledemo</param-value> 
     </init-param> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>JAX-RS REST Servlet</servlet-name> 
     <url-pattern>/services/*</url-pattern> 
    </servlet-mapping> 
    <welcome-file-list> 
     <welcome-file>index.jsp</welcome-file> 
    </welcome-file-list> 
</web-app> 
関連する問題