Thought I'd contribute this variation on the example from M.Abdel-Aziz
(thanks so much for the inspiration).   It was written using 2.0m6.  There
are 3 code fragments:  1. the routing, 2. a file upload ServerResource, 3.
code that inserts the uploaded file and its name (as specified in the URI)
into a blob in a mysql database table.  There are a couple more notes at the
end.

                // 1.  file upload routing in a Restlet Application

                Router router = new Router(getContext()); 
                router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
                router.setRoutingMode(Router.MODE_BEST_MATCH); 

                Router uploadRouter = new Router(getContext());                 

                uploadRouter.attach("", FileUploadResource.class);
                uploadRouter.attach("/name/{name}", FileUploadResource.class);  

                final ChallengeAuthenticator uploadGuard = new
ChallengeAuthenticator(this.getContext(), ChallengeScheme.HTTP_BASIC, 
                                "Restful Access -- Please supply your 
credentials");
                uploadGuard.setVerifier(myVerifier); 
                uploadGuard.setNext(uploadRouter);
                router.attach("/fileuploads",uploadGuard);

/** 
 * 2.  Resource that manages uploading files. 
 * Sample curl used to test this beast:
 * 
 * curl -v -u name:password 
http://127.0.0.1/myResource/fileuploads/name/test.jar  -F
name=@/Users/ty/Desktop/test.xml  -X POST
 *
 */
public class FileUploadResource extends ServerResource {
        private static Logger myLog = 
Logger.getLogger(FileUploadResource.class);
        private Request request;
        private String fileName = "";
        private CMInfo cmi = null;

        @Override  
        protected void doInit() throws ResourceException {  
                getVariants().add(new Variant(MediaType.MULTIPART_ALL)); 

                request = getRequest();
                ClientInfo cli = request.getClientInfo();
                ChallengeResponse cr = request.getChallengeResponse();
                cmi = new CMInfo(cr.getIdentifier(), cli.getAddress(), null);

                fileName = (String) getRequest().getAttributes().get("name");

                if(request.getMethod() != org.restlet.data.Method.POST) {
                        setStatus(Status.CLIENT_ERROR_CONFLICT);  
                }
                else {
                        setStatus(Status.SUCCESS_OK);
                }
        } 

        @Post
        public void uploadIt(Representation file) { 

                try {
                        FileItemFactory factory = new DiskFileItemFactory(); 
                        RestletFileUpload fileUpload = new 
RestletFileUpload(factory); 

                        FileItemIterator iter = 
fileUpload.getItemIterator(file);

                        if (iter.hasNext()) { 
                                FileItemStream item = iter.next();

                                if (!item.isFormField()) { 
                                        
myLog.info("ContentType:"+item.getContentType());
                                        myLog.info("file:"+item.getName());

                                        Attachment.uploadAttachment(cmi, 
item.openStream(), fileName);  
                                } 
                        } 
                }
                catch (Exception e) {
                        myLog.info("uploadIt exception:"+e);
                }

                setStatus(Status.SUCCESS_CREATED);  // assume works for now
        } 
}

        // 3. a function to save an uploaded file to a mySql attachments table

        public static int uploadAttachment(CMInfo cmi, InputStream inStream, 
String
attachmentName) {
                InputStream is = null;
                int attachmentId = -1;
                DataSource ds = MyUtils.getDataSource();
                java.sql.Connection conn = null;
                PreparedStatement ps = null;
                String sqlString = null;
                int fileLength = 0;
                
                try {
                        fileLength = (int) inStream.available();

                        if(StringUtils.isNotBlank(attachmentName)) {
                                sqlString = "INSERT INTO attachments (filename, 
contents) VALUES(?, ?)
";

                                conn = ds.getConnection();
                                ps = StatementFactory.getStatement(conn, 
sqlString, cmi);
                                ps.setString(1, attachmentName);
                                ps.setBinaryStream(2, inStream, fileLength);
                                ps.executeUpdate();

                                sqlString = "SELECT LAST_INSERT_ID() as autoId 
";
                                ps = StatementFactory.getStatement(conn, 
sqlString, cmi);
                                ResultSet rs = ps.executeQuery();
                                if (rs.next()) {
                                        attachmentId = rs.getInt("autoId");
                                }                               
                        }
                }
                catch (Exception e) {
                        myLog.info("Exception: " + e.getMessage());
                }
                finally {
                        try {
                                if (ps != null) { ps.close(); }
                                if (ds != null) { ds.closeConnection(conn); }
                        }
                        catch (Exception e) {}
                }

                // here's where things get dicey.  the binarystream upload can 
fail
without an exception being thrown.
                // so we'll test the blob's length to determine if the upload 
succeeded,
just to be sure
                try {
                        sqlString = "SELECT contents FROM attachments WHERE 
attachment_id=?";
                        conn = ds.getConnection();
                        ps = StatementFactory.getStatement(conn, sqlString, 
cmi);
                        ps.setInt(1, attachmentId);

                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                                is = rs.getBinaryStream("contents");
                                fileLength = is.available();
                        }       
                }
                catch (Exception e) {
                        myLog.info("Exception: " + e.getMessage());
                }
                finally {
                        try {
                                if (ps != null) { ps.close(); }
                                if (ds != null) { ds.closeConnection(conn); }
                                if (is != null) { is.close(); }
                                // close parameter inStream in calling function
                        }
                        catch (Exception e) {
                        }
                }
                
                return (fileLength == 0)?-1:attachmentId;
        }

We use this code to allow users to upload files that can be "attached" to
other info we are storing.  For example, you can attach a po pdf to a
purchase order.  The code runs in a Tomcat servlet environment, so
myResource has a servlet mapping in web.xml that points to the Restlet
application that the router code is part of.  Be sure to include the
org.apache.commons.io.jar file. CMInfo is used to log user info on database
updates, but it is not vital to the example.  We're not using Restlet
logging since we already had been using log4j for our other servlets.


-- 
View this message in context: 
http://n2.nabble.com/Upload-to-Directory-tp2438898p4191642.html
Sent from the Restlet Discuss mailing list archive at Nabble.com.

------------------------------------------------------
http://restlet.tigris.org/ds/viewMessage.do?dsForumId=4447&dsMessageId=2431725

Reply via email to