FileDownload - Download string to file

Hi,
I want to download some content to a file.
I have created a FileDownload element in my layout and i have bound the resource property.
In my context node i have made a value attribute of type <b>com.sap.tc.webdynpro.progmodel.api.IWDInputStream</b>
For this value attribute i have set the calculated property to true and also read only. In the generated getter i have the following code:
String test = "" + System.currentTimeMillis();
IWDInputStream is = WDResourceFactory.createInputStream(test.getBytes("UTF-8"));
return is;
in wdDoInit i have bound the WDResource to the attributepointer of my inputstream value attribute and i did: wdContext.currentContextElement.setResource(resource);
The code works fine, the only problem is that the content of the file is ALWAYS the value generated the first time the getter is called....(Its also possible he only calls the method only the first time. i'm not sure, but he should call the getter automatically when i click my FileDownload element because the Resource needs the inputstream then)
Is there some cache i need to clear every time or so? Or am i missing something?
The code below does work, but i want to have working with the FileDownload Element too:
String bla = "" + System.currentTimeMillis();
IWDResource resource = WDResourceFactory.createResource(bla.getBytes(), "test.xml", WDWebResourceType.TXT);
IWDWindow window = wdComponentAPI.getWindowManager().createNonModalExternalWindow(
               resource.getUrl(WDFileDownloadBehaviour.ALLOW_SAVE.ordinal()), "Window title");
window.show();
window.destroyInstance();
With any of above methods, is it possible to close the window that is generated when i save?
Greetz,
J.

Hi,
I just found the solution for problem of downloading the same content. The thing is if the data has change but the resource of the file doesn't. One more problem is that if you want to use FileInputStream for downloading file, you could not close it. However, method createResource of WDResourceFactory has three constructor, you need to use the one (FileInputStream,<<filename>>,<<resourceType>>, true); (true option is to flush the FileInputStream and close it).
Finally, you need to put the part of code for supplying the resource at the part of method wdDoModifyView(). The reason to put it here is for every even need to load the view again, and when loading it, the resource will also be reloaded too. If not, the resource of the file will be not load and be cached in the memory.
here is the part of code.
public static void wdDoModifyView( IPrivateTestExport_Main wdThis, IPrivateTestExport_Main.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime){
try {
//    ===== WORKAROUND CODE ===========================
//    The image file 'sap.jpg' is deployed with the Web Dynpro project
//    (under src/mimes/Components...). The resource path (URL) for this mime
//    objects can be accessed using the WDURLGenerator service.
  String resourcePath = "testfile.txt";
//    retrieve resource object for given resource path and create
//    a new object of type IWDResource by invoking the
//    WDResourceFactory API.
  IWDResource resource =
  WDResourceFactory.createResource(
  new FileInputStream(new File(resourcePath)),
   "testfile.txt",
   WDWebResourceType.TXT,
   true);
//    true: flush file input stream so that it gets closed immediately
//    ===== SIMPLE CODE only running in NW 04s Stack 12 ========
//    Based on a bug this simple coding cannot be implemented. The bug
//    will be fixed within NW04s SP Stack 12.
/*IWDResource resource =
WDWebResource.getWebResource(
wdComponentAPI.getDeployableObjectPart(),
FileDownloadView.FILE_EXT,
FileDownloadView.FILE_NAME);*/
//    store resource object in context attribute 'FileResource'
  wdContext.currentResourceElement().setDownloadFileResource(resource);
} catch(FileNotFoundException ex){

Similar Messages

  • How to authenticate a JWS Client download of jar files on a web server

    Here is a history of how i tried to implement the auth system:
    The resources(jar files) cannot be downloaded by any HTTP client from the server without some authentication method.
    As JWS is not reliable when using cookies (only 1.5 supports them, but with problems when in JNLP file i specify j2se version=older that 1.5) , i implemented another mecanism that works like this:
    1. 1.The template JNLP looks like this
    <?xml version="1.0" encoding="utf-8"?>
    <jnlp codebase="http://10.3.0.62/" href="mapped/#JWS_CODE#___#PLATFORM#___app2.2.jnlp">
        <information>
           bla bla
        </information>
        <security>
            <all-permissions/>
        </security>
        <resources>
            <j2se version="1.4"/>
            <jar href="http://10.3.0.62/mapped/gui.jar?jwsid=#JWS_CODE#" version="2.2"/>
            <jar href="http://10.3.0.62/mapped/data.jar?jwsid=#JWS_CODE#" version="2.2"/>
            <jar href="http://10.3.0.62/mapped/log4j.jar?jwsid=#JWS_CODE#"/>
        </resources>
        <application-desc main-class="com.bet.blues.gui.Application">
            <argument>-host</argument>
            <argument>ursus</argument>
            <argument>-port</argument>
            <argument>17771</argument>
        </application-desc>
    </jnlp>2. All resources found in /mapped/ directory are mapped to JWSServlet
    3. The users login to a site , clik on link , /mapped/app2.2.jnlp , the servlet checks if the session is active , gets the PLATFORM form browser request header , gets the JWSCODE for the logged user, replaces this in the template, and returns it to the client
    4.Now after the 1st download the JNLP file is opened by JWS Client , that checks for latest version , requesting the JNLP file again
    like this:
    GET http://10.3.0.62/mapped/f12ks21092___windows___app2.2.jnlp5.Now the servlet sees the the request has a JNLP file name with an ID and PLATFORM, and serves the JNLP as before
    6.The JWS Client will request for JAR Files
    GET http://10.3.0.62/mapped/gui.jar?jwscode=f12ks21092?version-id=2.2Note: that i have forced JWSID parameter in the URL, that's why the query string contains 2 "?"
    - forcing this is because the mapped/*.jar is redirected JnlpDownloadServlet that supports versions , diffs - i cannot use 'version' to put there the jswid param(e.g .../mapped/gui.jar version="fk12ks21092_2.2" because the JnlpDownloadServlet will not find this version , and if JWS Servlet will redirect to JnlpDownloadServlet with correct version param in request, the JWS Client will raise an exception because version responded is not right(JNLPDownloadServlet marks in response HTTP header the version of the jar so JWS CLient will chek it)
    JWS Client expects version 'fk12ks21092_ver2.2'; to correct this i should modify the JnlpDownloadServlet and i shouldnt
    THE PROBLEM :
    on older versions than 1.5 JWS Client raises an exception because it wants to create a temp file named
    " gui.jar?jwscode=f12ks21092" because it contains "?"
    Only with 1.5 that seems to parse the jar name until it meets "?" char :(
    Thats why i wanted to send an error to the client to upgrade to Java Web Start 1.5
    Now, maybe u have a solution to this problem...
    All i want is a solution to let JWS Client download jars only if the user is authenticated by some mecanism....and also support the versioning system.
    Also:
    Note that the jar names must preserve on the client JWS Cache dir ( i cannot use the same method to pass the JWSCODE when requesting the JARS as when requesting the JNLP).

    You need to look into JAAS

  • Downloading a text file from application server

    Hi Freinds,
    I am genarating a text file in our application server (Folder /usr/sap/dbi/) I need to download this text file in my destop pc or some other windows server.
    What do I have to do? What is the procedure, Pls help.
    If someone have sample code, pls send.
    We are running SAP ECC5.0 on an iSeries (AS/400) Database DB2/400.
    Regards
    Thanura

    Hi,
    try this:
    REPORT ZGRO_TEST.
    DATA: DATEI_A(30) TYPE C VALUE '/tmp/matnr.txt'.
    DATA: DATEI_PC TYPE STRING VALUE 'C:\MATNR.TXT'.
    DATA: ITAB        TYPE TABLE OF MARA WITH HEADER LINE.
    START-OF-SELECTION.
      PERFORM DATEI_EINLESEN.
      PERFORM DATEI_DOWNLOAD.
    FORM DATEI_EINLESEN.
      OPEN DATASET DATEI_A FOR INPUT IN TEXT MODE.
      IF SY-SUBRC NE 0. STOP. ENDIF.
      DO.
        READ DATASET DATEI_A INTO ITAB.
        IF SY-SUBRC <> 0. EXIT. ENDIF.
        APPEND ITAB.
      ENDDO.
      CLOSE DATASET DATEI_A.
      IF SY-SUBRC NE 0. STOP. ENDIF.
    ENDFORM.                    "DATEI_EINLESEN
    FORM DATEI_DOWNLOAD.
    Datei downloaden
      CALL METHOD CL_GUI_FRONTEND_SERVICES=>GUI_DOWNLOAD
        EXPORTING
          FILENAME                = DATEI_PC
          FILETYPE                = 'ASC'
        CHANGING
          DATA_TAB                = ITAB[]
        EXCEPTIONS
          FILE_WRITE_ERROR        = 1
          NO_BATCH                = 2
          GUI_REFUSE_FILETRANSFER = 3
          INVALID_TYPE            = 4
          NO_AUTHORITY            = 5
          UNKNOWN_ERROR           = 6
          HEADER_NOT_ALLOWED      = 7
          SEPARATOR_NOT_ALLOWED   = 8
          FILESIZE_NOT_ALLOWED    = 9
          HEADER_TOO_LONG         = 10
          DP_ERROR_CREATE         = 11
          DP_ERROR_SEND           = 12
          DP_ERROR_WRITE          = 13
          UNKNOWN_DP_ERROR        = 14
          ACCESS_DENIED           = 15
          DP_OUT_OF_MEMORY        = 16
          DISK_FULL               = 17
          DP_TIMEOUT              = 18
          FILE_NOT_FOUND          = 19
          DATAPROVIDER_EXCEPTION  = 20
          CONTROL_FLUSH_ERROR     = 21
          NOT_SUPPORTED_BY_GUI    = 22
          ERROR_NO_GUI            = 23
          OTHERS                  = 24.
      IF SY-SUBRC NE 0. STOP. ENDIF.
    ENDFORM.                    "DATEI_DOWNLOAD
    Regards, Dieter

  • Warning while downloading an Excel file from WD ABAP

    Hi folks,
    In one of requirements, Client wants to download all the data that is appearing on the screen ( WD ABAP Application ) to an Excel with a layout in different manner.
    We achieved this with Simple Transformations.
    Now the question is while downloading the excel file, the framework/other  is throwing an Warning like
    " The file you are trying to open, 'info.xls', is in a different format than specified by the extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now? "
    Note: All the users of my client are using MS Office 2002 / 2003.
    I am using the following code........!
    *------ Call Transformation for Excel OUTPUT
      CALL TRANSFORMATION ZEXCEL_OUTPUT
          SOURCE
                 t_dates     = t_dates
                 t_info        = t_info
          RESULT XML l_xml_string.
    REPLACE ALL OCCURRENCES OF '<?xml version="1.0" encoding="utf-16"?>'  l_xml_string WITH '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?>'.
    **-- Call Function Module for converting string data to XSTRING
      CALL FUNCTION 'SCMS_STRING_TO_XSTRING'
        EXPORTING
          text           = l_xml_string
          mimetype = 'application/xml'
        IMPORTING
          buffer      = l_xml_xstring
        EXCEPTIONS
          failed   = 1
          OTHERS   = 2.
      CALL METHOD cl_wd_runtime_services=>attach_file_to_response
        EXPORTING
          i_filename       = 'info.xml'
          i_content        = l_xml_xstring
          i_mime_type   = 'application/vnd.ms-excel'.
    With this code I am generating a file of type XML SPREADSHEET 2003. While opening this file I am getting the above message which the user unwanted......
    Can any one help me on this -
    > How to avoid this warning?
    Thanks and Regards,
    Aneel Danda
    Edited by: danda aneel on Jul 13, 2010 1:43 PM

    Firstly, Thanks for Your quick Response, Thomas.
    Even though what ever may be the file name I am passing either info.xml or Info.xls , In error info.xls is coming.
    Kindly provide me an alternative on this  XML doesn't seem like it would match the 'application/vnd.ms-excel'.
    what is the supported format.?
    Similarly, It is not considering the UTF-8 / UTF-16 for xml.........same result is appearing in the output.
    Edited by: danda aneel on Jul 14, 2010 7:52 AM

  • How to download a .pdf file from a JavaMail application?

    hi to all,
    iam unable to download a .pdf file from a mailserver using
    my javamail application.i have downloaded all kind of files except .pdf.
    my code snipnet:
    public static void dumpPart(Part p) throws Exception {
    //     if (p instanceof Message)          dumpEnvelope((Message)p);
              System.out.println("CONTENT-TYPE: " + p.getContentType());
              Object o = p.getContent();
              if (o instanceof String) {
                   System.out.println("This is a String");
                   System.out.println((String)o);
                   } else if (o instanceof Multipart) {
                        System.out.println("This is a Multipart");
                        Multipart mp = (Multipart)o;
                        int count = mp.getCount();
    System.out.println("****************************************");
    System.out.println("count" + count);
    System.out.println("****************************************");
                        for (int i = 0; i < count; i++){
                             System.out.println("CONTENT-TYPE: " + p.getContentType());
                             dumpPart(mp.getBodyPart(i));
                        } else if (o instanceof InputStream) {
                             System.out.println("This is just an input stream");
                             InputStream is = (InputStream)o;
                             String filename=System.currentTimeMillis()+".exe     ";
                             FileOutputStream fos=new FileOutputStream(filename);
                             int c;
                             while ((c = is.read()) != -1)
                                  //System.out.write(c);
                                  fos.write((char)c);
    }//dumpPart
    what's wrong with this code?
    Nagaraju.G

    fos.write((char)c);Converting the byte to a char is unnecessary and probably harmful. Just do this: fos.write(c);

  • Download a text file from JSP (Urgent Please!)

    Hi,
    I have a issue with this JSP, I need to download a txt file from my webserver to the pc client, the page shows the dialg box but appear the filename (list.jsp) of my jsp instead of the txt file.
    If I click the save buton save the list.jsp page; if I click in the open buton, then appear again the dialg box and now appear the url (download.jsp?filename=...) and if I click in the save button now I can save my txt file in the local pc.!!!!
    Any ideas ??
    list.jsp --> is the jsp from the download.jsp is run.
    download.jsp
    <%@ page import="java.io.*,javax.servlet.*,java.util.* "%><% String filename = request.getParameter("filename");
    response.setContentType("application/download");
    String value = "attachment; filename=\"" + filename + "\";" ;
    response.setHeader("Content-Disposition",value);
    int iRead;
    FileInputStream stream = null;
    try {
    File f = new File("C://test//" + filename);
    stream = new FileInputStream(f);
    while ((iRead = stream.read()) != -1) {
    out.write(iRead);
    out.flush();
    finally {
    if (stream != null) {
    stream.close();
    %>

    Maybe try no quotes around the content disposition header?
    Also, I'm not sure that application/download would be the best content type, maybe "application/octet-stream" instead. You should also probably explicitly set the Content-Length header to the file size.

  • Download a XML file from Web Services Using Flex

    Hi All...
    I am new for flex, im developing a windows application using Flex/Air, i have connected the web services with user authentication, now I want to download a xml file using web services in flex,
    how can i do this?? please reply...
    Thanks in advance
    Vasanth

    Hi All....
    I have done this myself using sample tutorials...
    here is the code for your reference guys
              plyLoginName = txtEmailIdDownload.text;                
                     var urlpath:String = new String("your url p?LoginName=");
                    urlpath = new String(urlpath.concat(plyLoginName));
                    urlpath = new String(urlpath.concat("&PlayerType="));
                    urlpath = new String(urlpath.concat(chkseasonvalue));
                    Alert.show(urlpath);
                var request:URLRequest = new URLRequest(urlpath)
                var fileRef:FileReference = new FileReference();           
                fileRef.download(request,"yourfilename.xml");
                Alert.show('File downloaded Successfully');   
                 txtEmailIdDownload.text = "";
                txtPWDownload.text = "";
    thanks
    Vasanth

  • VBA How to download a generated file from IE

    Hi guys,
    Apologies if this is an easy one, I couldn't find anything that helped me with my problem and was hoping someone might point me in the right direction for which object/argument to use.
    I'm trying to automate the downloading of a report, it will be a CSV file however it's not a static address (i.e. www.hello.com/files/goodbye.csv)
    The website is a CMS with database backend and upon clicking a button, the report is generated and the user will be prompted to download a resulting file (once it has been prepared).
    It is this action that I am trying to automate, however I'm not sure how to get IE to click the button and automatically saving instead of prompting the user at all (ideally this will be done with IE Visible being false in the end).
    Any help would be greatly appreciated!
    Best regards,
    Jeff.

    You can use an API to do the work too!
    Option Explicit
    Public Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, ByVal lpWindowName As String) As Long
    Public Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" ( _
    ByVal hWnd1 As Long, ByVal hwnd2 As Long, _
    ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
    Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
    ByVal hWnd As Long, _
    ByVal wMsg As Long, _
    ByVal wParam As Long, _
    lParam As Any) As Long
    Public Declare Function PostMessage Lib "user32.dll" Alias "PostMessageA"
    ByVal hWnd As Long, _
    ByVal wMsg As Long, _
    ByVal wParam As Long, _
    ByVal lParam As Long) As Long
    Public Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As
    Long) As Long
    Public Declare Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
    Public Const TCM_SETCURFOCUS As Long = &H1330&
    Public Const BM_CLICK As Long = &HF5&
    Private Const WM_COMMAND As Long = &H111
    Sub Download()
    Dim i As Long, res As Long
    Dim hWndUI As Long, hWndBtn As Long
    Dim timeOut As Double
    Const cClsName As String = "#32770" ' same classname for all the control
    windows we'll need
    ReDim aWinText(1 To 3) As String
    aWinText(1) = "File Download - Security Warning"
    aWinText(2) = "Save As"
    aWinText(3) = "Download complete"
    ' 1, get the File download window and click Save
    ' 2, get the Save As window and click Save
    For i = 1 To 2
    hWndUI = 0
    timeOut = Timer + 5
    While hWndUI = 0 And Timer < timeOut
    Sleep 100&
    hWndUI = FindWindow(cClsName, aWinText(i))
    Wend
    If hWndUI = 0 Then
    ' eg bad url
    Err.Raise 12345, , "didn't get " & vbCr & aWinText(i)
    End If
    SetForegroundWindow hWndUI
    Sleep 100&
    hWndBtn = FindWindowEx(hWndUI, 0&, "Button", "&Save")
    Sleep 200&
    res = SendMessage(hWndBtn, TCM_SETCURFOCUS, 1, ByVal 0&)
    'res = SendMessage(hWndBtn, BM_CLICK, ByVal 0&, ByVal 0&)
    res = PostMessage(hWndBtn, BM_CLICK, ByVal 0&, ByVal 0&)
    res = SendMessage(hWndBtn, WM_COMMAND, 0&, 0&)
    Next
    ' 3, wait until Download complete appears
    hWndUI = 0
    timeOut = Timer + 10 ' increase timeOut with bigger files
    While hWndUI = 0 And Timer < timeOut
    hWndUI = FindWindow(cClsName, aWinText(3))
    Wend
    ' optional open folder
    hWndBtn = FindWindowEx(hWndUI, 0&, "Button", "Open &Folder")
    res = SendMessage(hWndBtn, TCM_SETCURFOCUS, 1, ByVal 0&)
    res = PostMessage(hWndBtn, BM_CLICK, ByVal 0&, ByVal 0&)
    ' res = SendMessage(hWndBtn, BM_CLICK, ByVal 0&, ByVal 0&)
    res = SendMessage(hWndBtn, WM_COMMAND, 0&, 0&)
    DoEvents
    End Sub
    Sub Test1()
    Dim url As String
    Dim objIE As Object
    On Error GoTo errH
    url = "http://social.microsoft.com/Forums/getfile/25241/"
    ' iso IE suggest add a WebBrowser control to a sheet or a userform
    ' and use that rather than starting an instance of IE
    Set objIE = CreateObject("internetexplorer.application")
    objIE.Navigate url
    Download
    done:
    On Error Resume Next
    objIE.Quit
    Exit Sub
    errH:
    MsgBox Err.Description
    End Sub
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

  • Open hub destination to download the output file into R/3

    Hi Guys,
                 I have a requirement where i need to down load the data from my BW cube to R/3.For this i am using Open hub destination.
    While creating the open hub destination we have option called RFC Destination(in that i have selected destination as my R/3 system).When i execute my DTP it is saying the load is successful and it is showing the no.of records transfered.
    But i am not able to find where this data is getting transfered From BW cube to R/3 system using open hub.

    Hi Friends,
    I have one Query on WDJ. Here I have two requirements.
    I have done click on u201CExport Excelu201D Button that data was download into Excel file Now my requirement is click on Save Button that file will save into (/exchange/CED) this path of R/3 System.
    CED -
    >is R/3 System ID
    Under System id we can save this file.
    Here EP Server and R/3 Servers in Diff Systems.
    I was write codeing
    InputStream text =      null;
         int temp = 0;
         try
         File file =      new File(wdContext.currentContextElement().getResource().getResourceName().toString());
    //       String File = "abc.xls";
    //       String file = "anat" + ".xls";
         wdComponentAPI.getMessageManager().reportSuccess("File::"+file);
         FileOutputStream op =      new FileOutputStream(file);
    //       FileOutputStream op = new FileOutputStream("D://usr//sap//BPE//"+file);
    //       FileOutputStream op = new FileOutputStream("D://KumarDev-BackUp//"+file);
         wdComponentAPI.getMessageManager().reportSuccess("op::"+op);
         if (wdContext.currentContextElement().getResource()!= null)
         text = wdContext.currentContextElement().getResource().read(false);
         while((temp=text.read())!= -1)
         op.write(temp);
         op.flush();
         op.close();
    //        path = file.getAbsolutePath();
         path =      "/exchange/CED/"+file;
         wdComponentAPI.getMessageManager().reportSuccess("path:"+path);
         catch(Exception ex)
              wdComponentAPI.getMessageManager().reportSuccess("ex.printStackTrace()");
    My Req is that file will saved in this path (path =      "/exchange/CED/"+file; )
    Regards
    Vijay Kalluri

  • Download several large files - get CONTROL_FLUSH_ERROR

    Dear all,
    I want to download several large files from the application server to frontend with function module GUI_DOWNLOAD. I use a loop over the several filenames and download the files with following code:
      DATA: l_append        TYPE as4flag,
                 l_count         TYPE i,
                 l_max           type i    value 50000,
                 ls_ziel         TYPE string,
                 ls_download_txt LIKE LINE OF gt_download_txt,
                 lt_download_tmp LIKE gt_download_txt.
      CONCATENATE p_front gs_sel_table-selname '.' 'txt' INTO ls_ziel.
      IF NOT gt_download_txt[] IS INITIAL.
        LOOP AT gt_download_txt INTO ls_download_txt.
          APPEND ls_download_txt TO lt_download_tmp.
          IF l_count = l_max.
    CALL of FUNCTION MODUL GUI_DOWNLOAD    
            REFRESH lt_download_tmp[].
            CLEAR l_count.
            l_append = 'X'.
          ENDIF.
          l_count = l_count + 1.
        ENDLOOP.
    If I only download one large file, there is no problem. But when I want to download more then one file the function module returns the error CONTROL_FLUSH_ERROR.
    I can not say at which file the error occurs (2nd, 3rd, ...) I think it depends on the file size. Several smaller files are no problem. At two large files I get the error.
    Does anyone has an idea?
    Kind regards,
    Sven

    Hi,
    Please check this thead perhaps it may help.
    Re: CONTROL_FLUSH_ERROR with GUI_DOWNLOAD
    Regards,
    Ferry Lianto

  • Problem with downloading a PDF file from a webserver run on Linux

    Hi,
    I've written a simple functionality that manages file attachments.
    Everything works fine (attaching, downloading, deleting) when the webserver runs on Windows.
    However when I deployed the code to the Resin webserver run on Linux and use the Win browser to connect to the app, the downloading of PDF file doesn't work (uploading and downloading of txt, doc, xls, jpg files is OK).
    The downloaded PDF file is almost twice as big as original (~28KB when original is ~12KB) and it can't be open.
    I guess it is the problem of writing to the output stream of HttpServletResponse but I can't localize the problem.
    Here is the code I use for downloading file:
    private boolean downloadFile(HttpServletResponse response, String filePath,
                   String originalFilename) {
         File file = new File(filePath);
         String contentType = URLConnection
                   .guessContentTypeFromName(originalFilename);
         // If the content type is unknown set the default value.
         if (contentType == null) {
              contentType = "application/octet-stream";
         BufferedInputStream input = null;
         BufferedOutputStream output = null;
         try {
              input = new BufferedInputStream(new FileInputStream(file));
              int contentLength = input.available();
              response.reset();
              response.setContentLength(contentLength);
              response.setContentType(contentType);
              response.setHeader("Content-disposition", "attachment; 
                           filename=\""+ originalFilename + "\"");
                output = new BufferedOutputStream(response.getOutputStream());
              int bufSize = 10000;
              byte[] buf = new byte[bufSize];
              int bytesNo = 0;               
              while ((bytesNo = input.read(buf, 0, bufSize)) != -1) {
                   output.write(buf, 0, bytesNo);
              output.flush();
              input.close();
              output.close();
         } catch (IOException e) {
              log.debug(e.getMessage());
              e.printStackTrace();
    }Can you point any problem?
    Thanks in advance,
    Ala

    matali wrote:
              int bufSize = 10000;
              byte[] buf = new byte[bufSize];
              int bytesNo = 0;               
              while ((bytesNo = input.read(buf, 0, bufSize)) != -1) {
                   output.write(buf, 0, bytesNo);
    This piece is completely wrong and doesn't work for files bigger than 10000 bytes. Replace it by
    byte[] buffer = new byte[10240]; // 10KB exactly.
    int length = 0;
    while ((length = input.read(buffer)) > 0) { // Read next 10KB of input to buffer.
        output.write(buffer, 0, length); // Write specified length of buffer to output.
    }Or just use output.write(input.read()) in a loop of the contentLength as you're alredy using BufferedInputStream/BufferedOutputStream.
    Another thing, the method is declared to return a boolean, but it actually doesn't? I would just let it throw an exception in case of failure instead of returning a boolean and let the calling method handle the exception.

  • HT2488 How do I create a workflow in Automator or a script in AppleScripts to download an excel file from a specific webpage?

    I would like to create a workflow in Automator or a script in AppleScript (or a combination of the two), that opens Safari to a specified page and downloads an excel file from this page and saves the downloaded document to my desktop.
    Is this something that be done? If so, how?
    I have so far been able to build a workflow in Automator to open Safari and added an AppleScript that takes Safari to a specific page that has an Excel document.
    I can't figure out where to go from here... Any help would be apprecitated.
    Thanks!

    Would you have the web address the excel sheet is on?
    Is there a simular web page you could point to if not?
    Would there be a copy of the file on an FTP page.  This would be easier. 
    curl
    http://www.cyberciti.biz/faq/mac-os-x-terminal-download-file/
    http://www.thegeekstuff.com/2012/04/curl-examples/
    http://curl.haxx.se/docs/manpage.html
    Macintosh-HD -> Applications -> Utilities -> Terminal
    # Press return to run a command.
    the curl is a terminal command ( Unix ).  It allows you to read a file off of the web.
    man curl
    provides cryptic information on the commnad curl.
    press the space bar to advance  a page.
    press letter to q to quit.
    What you may have to is to read in the web page as a text file.  Go "fishing" through the page to find the excel file you need.  Once you find the file, you can use curl to read the file.
    curl is a very full featured command.  (read complex to figure out ).
    It is easier to diagnose problems with debug information. I suggest adding log statements to your script to see what is going on.  Here is an example.
        Author: rccharles
        For testing, run in the Script Editor.
          1) Click on the Event Log tab to see the output from the log statement
          2) Click on Run
        For running shell commands see:
        http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
    on run
        -- Write a message into the event log.
        log "  --- Starting on " & ((current date) as string) & " --- "
        --  debug lines
        set desktopPath to (path to desktop) as string
        log "desktopPath = " & desktopPath
        set unixDesktopPath to POSIX path of desktopPath
        log "unixDesktopPath = " & unixDesktopPath
        set quotedUnixDesktopPath to quoted form of unixDesktopPath
        log "quoted form is " & quotedUnixDesktopPath
        try
            set fromUnix to do shell script "ls -l  " & quotedUnixDesktopPath
            display dialog "ls -l of " & quotedUnixDesktopPath & return & fromUnix
        on error errMsg
            log "ls -l error..." & errMsg
        end try
    end run

  • How to zip a folder containing subfolders with files and download the zip file in silverlght 4

    private void hbtnDownloadReceipt_Click(object sender, RoutedEventArgs e)
               try
                    string Docpath = "ClaimsDetails/" + "20tech" + "/" + PaymentAdviceUNo;
                    string dd = "ClaimsDetails/";
                    Uri uri = new Uri(Application.Current.Host.Source, "/" + Docpath);
                    Uri uri1 = new Uri(Application.Current.Host.Source, "/" + dd);
                    string path = uri.AbsoluteUri.ToString();
                    path1 = uri1.AbsoluteUri.ToString();
                    //HtmlPage.Window.Eval("window.open('" + path + "')");
                catch (Exception ex)
                    ex.Data.Clear();
    1) Here "path" is D:\\TL 24-12-2014 \\OfficeConnect_17_10\\OfficeConnect.Web\\ClaimsDetails\\20tech\\PaymentAdviceUNo.     
    2) In path "PaymentAdviceUNo" is the folder containing subfolders which i want to zip.
    Thanks in Advance.

    Hi,
    You can download a zip file like any files with the Webclient class, look at the details and examples in the msdn documentation for downloading content on demand it even talks about how to download and get a specific file from a zip archive.
    http://msdn.microsoft.com/en-us/library/cc189021(VS.95).aspx
    Besides,  if you want to list the files,you could check articles below:
    http://blogs.msdn.com/b/blemmon/archive/2009/11/25/reading-zip-files-from-silverlight.aspx
    Best Regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Problem on downloading a zip file

    I am having a problem on downloading a zip file(file size is about 2Mb). Sometimes I can get a complete file and can open the file, sometimes the zip file is chunked(the file size is smaller than the right one), so I can't open it.
    The file content is stored in a blob field. The code first goes to database get the blob as inputstream, then copy the inputstream into response.getOutputStream().
    The problem is unpredictable. Even for the same blob data, sometimes I can get working file, sometimes I just get crapped file.
    Could somebody help me out? I am struggling with it.
    Any input is appreciated!
    public class DownloadTextAction extends Action implements Serializable{
        private static Log log = LogFactory.getLog(DownloadTextAction.class);
        public ActionForward execute(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response) throws Exception
            ActionErrors errors = new ActionErrors();
            String batch_id = (String)request.getParameter("batch_id");
            String fileName = batch_id+".zip";
            try
    //          response.setContentType("application/octet-stream");
              response.setContentType("application/download");
      //        response.setContentLength(content.length());
    //          response.setHeader("Content-Disposition", "inline; filename=\""
    //                    + fileName + "\"");
              response.setHeader("Content-Disposition", "attachment; filename=\""
                        + fileName + "\"");
              InputStream in = untilService.getBlob(batch_id);         
              OutputStream out = response.getOutputStream();
              FileHelper.copy(in, out);
              out.flush();
              in.close();
              out.close();
            catch (Exception e)
              errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.detail", e.toString()));
              saveErrors(request, errors);
              log.error(e.toString());      
            return mapping.findForward(Constants.SUCCESS);
        }

    Maybe a fault in the missing FileHelper.copy() method?

  • Regarding download to text file

    Dear ABAP Gurus,
    I have requirement to download internal table to text file and put it on a strorade via ftp.
    The problem is, when i try to write long text into the file, i cannot write euro currency character 'u20AC', the 'u20AC' replaced by other character like 'ä.¬'
    But if I download to xls file (using GUI_DOWNLOAD to local storage), it works fine.
    Is there any solution on this matter?
    Are there other character that would replaced by characters just like euro currency character?
    Thanks in advance.
    Rgds.
    -g-

    Try this :
    - cl_abap_char_utilities=>horizontal_tab  is tab delimited, it's depent what is your separator
    - itab is your internal table, below is just sample
    DATA :  filenamex TYPE char50,
    DATA : l_string TYPE string.
    filenamex = '/itf/zsmart/test.txt
      OPEN DATASET filenamex FOR INPUT IN TEXT MODE
                   ENCODING DEFAULT.
      IF sy-subrc = 0.
        DO.
          CLEAR : l_string.
          READ DATASET filenamex INTO l_string.
          IF sy-subrc NE 0.
            EXIT.
          ELSE.
            SPLIT l_string AT cl_abap_char_utilities=>horizontal_tab
            INTO itab-key itab-otyp itab-sorg itab-dchl itab-div itab-soff
                 itab-cust itab-pon itab-podt itab-docdt itab-pymtr
                 itab-inco1 itab-inco2 itab-matnr itab-qty itab-batch
                 itab-plant itab-sloc itab-shppt itab-promo itab-sprom
                 itab-mpgrp itab-obtyp itab-objno.
            APPEND itab.
            CLEAR itab.
          ENDIF.
        ENDDO.
      ELSE.
        MESSAGE e000(zelog) WITH 'Error Reading File'.
      ENDIF.

Maybe you are looking for

  • Why do I have to declare my int outside the function?

    `Hi! I've writen the very simple class get_results with one methode test: public class Get_results {    protected int nb=0; public int test(int numb) {          //int nb=0;          nb=numb;          return nb;            }//End test }//End classthis

  • Kernel Panic during hdd intensive process

    Hi there, I have been suffering from kernel panic tipicaly during hdd intesinve process like fixing disk permission, but it often happen during shutdown phase. AHT extended version ran well indicating no problem. Onyx says startup disk should be fine

  • ADSL / router slowed Network copying ? help ?

    I have 5 computers on a small network: 3 Macs (OS 9.2.2) and 2 Windows PCs and a networked printer connected using a 8 port switching Hub. The PCs are accessed using Dave's Network 6 on Mac (3) . Each computer and the printer has its own TCP/IP addre

  • What hapenned to the MJPEG codec in Vision 2012 SP1?

    NOTE:  This discussion is about the 64 bit version of the Vision toolkit! NI has re-vamped its AVI functions in the latest Vision toolkit (2012 SP1).  At first glance, the new AVI functions work fine.  At least the 64 bit version now has a wider sele

  • Activation key did nada

    I purchased an AnyConnect 250 user license for my ASA.  I got the key electronically, and used cisco's site to create my activation key.  I entered my activation key via the ASDM.  I rebooted, and nothing changed.  I see that it's using the new activ