Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send file inside JSONObject to REST WebService

I want to send a file to webservice, but i need send more informations, so i want to send them with a json. But when i put a file inside my jsonObject i get an error saying that it isn't a string. My question is, should i take my File and convert to a string, then put inside my json and on web service take it and convert that string to a file? Or is there another simple way?

Here is my code:

Client:

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";
}

After all the answers, here is my code - thanks everyone:

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();
    }
}

Client

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));
    }

}
like image 469
user2486187 Avatar asked Sep 03 '13 19:09

user2486187


3 Answers

You should convert the file data to Base64 encoding and then transfer it, e.g. like this:

byte[] bytes = Files.readAllBytes(file_upload.toPath());
dados.put("File", DatatypeConverter.printBase64Binary(bytes));
like image 51
Moritz Petersen Avatar answered Oct 11 '22 03:10

Moritz Petersen


@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();
 }

and of the client side (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();
like image 45
moshe beeri Avatar answered Oct 11 '22 01:10

moshe beeri


I know its an old post but I just thought I'd add a little to avoid the dependancy on external 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();
}
like image 34
Palmeta Avatar answered Oct 11 '22 02:10

Palmeta