Eclipse rap rich client Development Summary (9)-rap upload and download

Source: Internet
Author: User
Note: Eclipse rap rich client Development Summary-a series of articles are transplanted from my iteye blog. Later will directly update the http://jlins.iteye.com/

1. Upload

To upload a file to the server, you need to write the corresponding script on the client. The server needs to register the corresponding handle to accept the client's request.

Principle:

Rap upload and download are carried out through normal Web upload and download, but they are not the same as traditional Wen

1. Rap itself is running in a single thread and cannot be confused with the upload/download thread.

The method is as follows:

Upload: Traditionally, you can upload files to a specified directory. Rap cannot directly operate on the file stream to be uploaded. To obtain the uploaded data, you must first upload the data to the specified file, then let rap load the specified file.

Download: first generate the file to be downloaded to the specified directory through the rap program, and then load the file into a file stream through the rap program and send it to the client.

 

1. register the corresponding handler on the server

 

// Register upload Processing Event Handler manager = rwt. getservicemanager (); iservicehandler uploadhandler = new uploadservicehandler (); manager. registerservicehandler ("uploadservicehandler", uploadhandler); // $ NON-NLS-1 $

 

2. script call on the client

The current practice is to create the uploaded dialog, add the browser control in the dialog, and then write the uploaded Javascript script in the browser. The URL format of the script request can be created using the following code:

 

  private String createUploadUrl(String uploadFileName) {      StringBuffer url = new StringBuffer();      url.append(RWT.getRequest ().getContextPath());      url.append(RWT.getRequest ().getServletPath());      url.append( "?" ); //$NON-NLS-1$      url.append(IServiceHandler . REQUEST_PARAM );      url.append( "=uploadServiceHandler" ); //$NON-NLS-1$      url.append( "&fileName=" ); //$NON-NLS-1$      url.append(uploadFileName);      return url.toString();   }

3. Server Handler

Public class uploadservicehandler implements iservicehandler {public void Service () throws ioexception, servletexception {httpservletrequest request = rwt. getrequest (); Request. setcharacterencoding ("UTF-8"); string filename = request. getparameter ("FILENAME"); fileoutputstream o = NULL; bufferedreader bufferreader = NULL; inputstream in = NULL; try {In = request. getinputstream (); file F = NULL; try {f = new file (fileutil. gettempfilepathandname (rwt. getrequest (). getsession (). getattribute ("username "). tostring (), filename);} catch (exception e) {Throw new ioexception (E);} o = new fileoutputstream (f ); bufferreader = new bufferedreader (New inputstreamreader (in); string line = NULL; Boolean beginwrite = false; Boolean endwrite = false; while (line = bufferreader. readline ())! = NULL) {If (line. indexof (pricedomainbean. Class. getname ())! =-1) {If (! Beginwrite) {beginwrite = true;} else {endwrite = true ;}} if (beginwrite) {o. write (LINE + "\ r \ n "). getbytes () ;}if (endwrite) {break ;}} catch (ioexception e) {Throw e ;}finally {If (null! = O) {o. Close () ;}in. Close (); If (null! = Bufferreader) {bufferreader. close () ;}} httpservletresponse response = rwt. getresponse (); response. setcontenttype ("text/html; charset = UTF-8"); response. getwriter (). write ("<br> <Div align = center> <H2> upload successful! </H2> ");}}

2. Download

The download and upload methods are basically the same, except that the Server File is read to the local device, which is the opposite of the upload method.

1. register the corresponding handler on the server

// Register the download handling event iservicemanager manager = rwt. getservicemanager (); iservicehandler downloadhandler = new downloadservicehandler (); manager. registerservicehandler ("downloadservicehandler", downloadhandler );

 

2. Call in client Section

Write the JS request script in the bowser control. The URL requested by the script is as follows:

private String createDownloadUrl(String fileName) {        StringBuffer url = new StringBuffer();        url.append (RWT.getRequest ().getContextPath());        url.append (RWT.getRequest ().getServletPath());        url.append ( "?" );        url.append (IServiceHandler. REQUEST_PARAM );        url.append ( "=downloadServiceHandler" );        url.append ( "&fileName='+encodeURI('" );        url.append (fileName);        url.append ( "')" );        return url.toString();    }

3. Server Handler

public class DownloadServiceHandler implements IServiceHandler {   public void service() throws IOException, ServletException {      String fileName = URLDecoder.decode (            RWT.getRequest ().getParameter( "fileName" ), "UTF-8" );      String filePathAndName = null ;      try {         filePathAndName = FileUtil         .getTempFilePathAndName (RWT.getRequest ().getSession()                      .getAttribute( "userName" ).toString(), fileName);      } catch (Exception e) {         throw new IOException(e);      }      File file = new File(filePathAndName);      if (!file.exists()) {         return ;      }      HttpServletResponse response = RWT.getResponse ();      response.setHeader( "pragma" , "no-cache" );      response.setHeader( "cache-control" , "no-cache" );      response.setDateHeader( "Expires" , 0);      response.setCharacterEncoding( "UTF-8" );      response.setContentType( "text/html;charset=UTF-8" );      response.setHeader( "Content-Disposition" , "attachment;filename="            + new String(fileName.getBytes( "gb2312" ), "ISO8859-1" ));      try {         BufferedInputStream in = new BufferedInputStream(                new FileInputStream(filePathAndName));         ByteArrayOutputStream out = new ByteArrayOutputStream(1024);         byte [] temp = new byte [1024];         int size = 0;         while ((size = in.read(temp)) != -1) {            out.write(temp, 0, size);         }         in.close();         byte [] content = out.toByteArray();         response.setContentLength(content. length );         response.getOutputStream().write(content);      } catch (IOException ioe) {         throw new RuntimeException(ioe);      } finally {         try {            FileUtil.deleteTempFile (RWT.getRequest ().getSession()                   .getAttribute( "userName" ).toString(), fileName);         } catch (Exception e) {            throw new IOException(e);         }      }   }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.