private void writeMultiPart ( final String assetId , final AttachmentSummary attSummary , HttpURLConnection connection ) throws IOException , BadVersionException , RequestFailureException { final File fileToWrite = attSummary . getFile ( ) ; String boundary = "---------------------------287032381131322" ; byte [ ] startBytes = getStartBytes ( attSummary , boundary ) ; byte [ ] endBytes = getEndBytes ( attSummary , boundary ) ; long fileSize ; fileSize = AccessController . doPrivileged ( new PrivilegedAction < Long > ( ) { @ Override public Long run ( ) { return attSummary . getFile ( ) . length ( ) ; } } ) ; long contentLength = startBytes . length + endBytes . length + fileSize ; connection . setRequestProperty ( "Content-Type" , "multipart/form-data; boundary=" + boundary ) ; connection . setRequestProperty ( "Content-Length" , "" + contentLength ) ; connection . setRequestMethod ( "POST" ) ; connection . setDoOutput ( true ) ; OutputStream httpStream = connection . getOutputStream ( ) ; // Write the header httpStream . write ( startBytes ) ; httpStream . flush ( ) ; FileInputStream inputStream = null ; try { try { inputStream = AccessController . doPrivileged ( new PrivilegedExceptionAction < FileInputStream > ( ) { @ Override public FileInputStream run ( ) throws IOException { return new FileInputStream ( fileToWrite ) ; } } ) ; } catch ( PrivilegedActionException e ) { throw ( IOException ) e . getCause ( ) ; } byte [ ] buffer = new byte [ 1024 ] ; int read ; int total = 0 ; while ( ( read = inputStream . read ( buffer ) ) != - 1 ) { httpStream . write ( buffer , 0 , read ) ; total += read ; } if ( total != fileSize ) { throw new IOException ( "File size was " + fileSize + " but we only uploaded " + total + " bytes" ) ; } httpStream . flush ( ) ; } finally { if ( inputStream != null ) { inputStream . close ( ) ; } } httpStream . write ( endBytes ) ; httpStream . flush ( ) ; httpStream . close ( ) ; }
Adds a new attachment to an asset