Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a File Attachment in JSON Object

Tags:

java

json

html

file

Is it possible to embed a file attachment in a JSON Object. I have a HTML Form, which has several text field inputs and a file attachment. I want to send a JSON Object wrapping all these form data (including the file attachment) to the server.

Are there any particular libraries in Java available to do that? Can you give possible solution for this.

Thanks

like image 784
Chinthaka Dharmasiri Avatar asked Nov 01 '25 10:11

Chinthaka Dharmasiri


2 Answers

If you want to send the actual data of the file, you'd probably want to encode it as a base64 string and send that in your JSON - see fiddle for example of encoding it in javascript:

http://jsfiddle.net/eliseosoto/JHQnk/

Then you could do the opposite on your server-side using whatever language and/or libraries are appropriate.

like image 106
Starscream1984 Avatar answered Nov 04 '25 01:11

Starscream1984


Use MultipartEntity, someone else posted a similar question: How to send file in JSON on android? You could also consider saving the files on the server and sending a path/url to the file location where the other server can access them.

 public String SendToServer(String aUrl,File Filename)
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(filename);

            try 
            {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                entity.addPart("file", new FileBody(Filename));
                entity.addPart("video-title", new StringBody("Video"));
                entity.addPart("video-type", new StringBody("1"));
                httpPost.setEntity(entity);

                HttpContext context = new BasicHttpContext();
                // Bind custom cookie store to the local context
                context.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);

                HttpResponse response = httpClient.execute(httpPost, context);
                HttpEntity resEntity = response.getEntity();  
                String Response = "";
                if (response != null) 
                {    
                    Response = EntityUtils.toString(resEntity); 
                }
                return Response;
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }

            return "Exception";
        }
like image 25
Mr Boss Avatar answered Nov 04 '25 01:11

Mr Boss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!