Setting the file name of a resource to be downloaded

Hi,
I am trying to download files from the webserver to the client machine using code given below..
The filename is the path to the file to be downloaded to the client. Some parsing of the filename is required as I modify the filename to a particular format. I use the parsed filename to get the Mime type which is then set to the content type.
When I tested the code, the mime type is correct and also the file downloaded is corrext. But the browser prompts me to save the file with the name of the Url. Can I change this? I suppose setting of some http response header is needed.
public class ReadServlet extends GenericServlet {
    public void service(ServletRequest req, ServletResponse res){
               ServletContext context = this.getServletContext();
               //check doc_id and doc_ver_index
               String filename = (String)req.getAttribute("filename");
               if(filename == null ){
                    return;
               try{
                    File file = new File(filename);
                    int underscore = filename.lastIndexOf('_');
                    if(underscore!=-1){
                         filename = filename.substring(0, underscore);
                    String mimeType = context.getMimeType(filename);
                    if(mimeType == null){
                         mimeType = "application/octet-stream";
                    res.setContentType(mimeType);
                    InputStream in = null;
                    OutputStream out = res.getOutputStream();
                    byte[] buffer = new byte[1024*8];
                    try {
                         in = new BufferedInputStream(new FileInputStream(file) );
                         int ch;
                         while ((ch = in.read(buffer)) !=-1) {
                              out.write(buffer, 0, ch );
                    finally {
                         if (in != null){
                              in.close();
                         if(out!=null){
                              out.close();
               }catch(IOException ioe){
                    System.out.println(ioe.getMessage());
          return;
}Thanks
Rahul

Hi Rahul,
res.setHeader("Content-Disposition", "attachment; filename=\"" + your_file_name + "\"");
res.setContentLength(your_file_length);Good luck.

Similar Messages

  • Export Indd to EPS/JPG and set the file name  for EPS/JPG file

    Hi,
       When I export the INDD to JPG/EPS, I want to set the file name with pageNumber  for JPG/EPS files using javascript.
    For Example
    If I set the file name as EPSFile.eps, after exporting the indd(with 2 pages) to eps
    ,files are generating in the following name EPSFile_1.eps, EPSFile_2.eps.
    but I want to set the file name as EPSFile_001.eps and EPSFile_002.eps using javascript.
    anyone knows please reply for this.
    Regards,
    Mubeen

    Hi,
      I tried the following code.
    var JPGe = new File("Applications/PDF/JPG/file.jp");
    app.activeDocument.exportFile(ExportFormat.jpg, );
    when I use this code ,exported jpg file names are
    file.jpg, file1.jpg,file3.jpg.
    but ,I want the output file names as file_001,file_002,file_003,
    Thanks,
    Mubeen

  • Is there a way to automatically set the file name in Acrobat Properties when exporting a PDF from Indesign?

    When I used Quark to make a PDF, the title area in the PDF was automatically populated with the file name, there in the properties tab. We like use this area to confirm file names of original files, so we can keep track of drafts, (in case the file name of the PDF is changed, which our boss often does). Is there any way to set up InDesign to do the same?

    @stadlock – I think I know what you mean…
    You exported to PDF and changed the file name in the export dialog to a different one from the document name presented there the first time you exported that document. And in exports after that the new name will be presented in the dialog instead of the name of the document.
    What you can do against that?
    1. First time you want to export: Save before the document is exported. And do not save after it's exported with a new file name.
    2. After the new file name is already there in the export dialog:
    Type in the document name in the dialog. Export. Or abort after chosing a export preference. Save. Check again, if the document's file name is in the export dialog. If yes, procede like in suggestion #1. If not do a full export with the document's file name, save and then procede with suggestion #1.
    Uwe

  • How can I set the file name and folder for output to PDF from another application?

    I am developing an application in Microsoft Access where the printed reports are to be saved in PDF format for archive purposes. I can send the output to Adobe X, but the default file name is the Access report name and the folder selected is the one last used.
    What I need to do is to create the file with a specific name (which changes for each run) and to a specific folder (which also changes for each run).
    The language I'm using is Visual Basic for Applications which is located in an Access form that controls the report production.
    Any suggestions, please?

    Got it - many thanks.

  • Setting up the File Name of email Attachment from Received File Name

    Hello All,
    I have to send the Received File in attachment to an Email if there is any exception. Here I can attach the file, but I cannot set the file name of attachment as the Received File Name. Is there anyway of doing this without using custom pipeline component.
    Here I am using the Orchestration and SMTP Adapter.Any help is greatly appreciated.
    Thanks

    It might work if you use a custom pipeline component on your send port and in the Execute method populate the MIME.FileName property of the body part.
    Something like:
    public IBaseMessage Execute(IPipelineContext pc, IBaseMessage inmsg)
    string filename = inmsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties");
    inmsg.BodyPart.PartProperties.Write( "FileName", "http://schemas.microsoft.com/BizTalk/2003/mime-properties", "filename);
    return inmsg;
    You can take reference from similar post here
    SMTP - Setting attachment filename
    Anther good article with MIME is here
    Setting attachment filename with the SMTP Adapter
    For MIME case your SMTP message construct statement would be like below
    multipartMessage.MessagePart_1= InMSG;
    multipartMessage.MessagePart_2="This is message part2 as a string";
    multipartMessage(SMTP.Subject) ="Email From Dynamic Port";
    multipartMessage(SMTP.From) ="[email protected]";
    multipartMessage(SMTP.SMTPHost) ="yoursmypserver.com";
    multipartMessage.MessagePart_2(MIME.FileName) = "Attachment_Name";
    multipartMessage(SMTP.SMTPAuthenticate) =0;
    Thanks
    Abhishek

  • Setting dynamic file name in Receiver file adapter - not from payload

    Guys I just remember reading a weblog but can't find it now that I need it, on how to set the file name in message mapping dynamically but not using any payload field.
    Please let me know if you remember this.
    Thanks a lot,
    Viktor Varga

    also u can check in
    <a href="/people/jayakrishnan.nair/blog/2005/06/28/dynamic-file-namexslt-mapping-with-java-enhancement-using-xi-30-sp12-part-ii file name(XSLT Mapping with Java Enhancement) using XI 3.0 SP12 Part -II</a>
    <a href="/people/michal.krawczyk2/blog/2005/11/10/xi-the-same-filename-from-a-sender-to-a-receiver-file-adapter--sp14: The same filename from a sender to a receiver file adapter - SP14</a>

  • Can I script the changing of creation date, using the file name?

    Normally people are doing this in reverse, but let me paint the picture.
    I pulled 204 video files from an old HDD based JVC camera.  JVC records in .MOD format which iPhoto won't import.  I imported them into iMovie just fine, and iMovie even set the file name to clip-2007-11-04 04;42;29.mov which is great, but it now has a new creation date of whatever date I imported it.  Which then causes problem when I want the videos stored in iPhoto and sorted appropriately by creation date.
    I've used the application "A Better Finder Attributes 5" to individually edit the creation and modify, but I'm sure I don't want to do this 203 more times, as you can't just type in the date and time, you have to type in each part of the date/time, or select it on a calendar.
    I've used the application "Name Changer" to batch convert the file names to the format YYYYMMDDhhmm which would be helpful if I were going to use the terminal command touch -t, but again I don't want to have to type it in 203 more times, plus drag and drop the file into finder to populate the location.
    Now, if I were more handy with automator, or maybe some (any) scripting language this would be easy peasy.  I'd batch rename all the files to the YYYYMMDDhhmm.mov and then have a script that just took the file name, passed that to touch -t along with the file location, and a few seconds later, they would all be done!
    Anybody have any suggestions to how I can do this, and tips to what commands to use or ANY advice?  I'm more than happy to RTFM, but I have no idea which manual to read!
    Thanks

    If your file names are precisely as you have written, this script will do what you want.
    Copy the script into an AppleScript Editor document, select one or more files in a Finder window, return to the AS Editor and press Run.  Note: you will need to provide your password when the script runs.
    Make sure you have a backup of any files you are working on (try using duplicates first, perhaps). The script has no error handling.
    tell application "Finder"
              set FileList to selection
              repeat with theFile in FileList
                        set fileName to name of theFile
                        set filePath to quoted form of (POSIX path of (theFile as alias))
                        set crYear to text 6 thru 9 of fileName
                        set crMonth to text 11 thru 12 of fileName
                        set crDay to text 14 thru 15 of fileName
                        set crHour to text 17 thru 18 of fileName
                        set crMins to text 20 thru 21 of fileName
                        set crDate to crYear & crMonth & crDay & crHour & crMins
                        set shellString to "touch -t " & crDate & " " & filePath
      do shell script shellString with administrator privileges
              end repeat
    end tell

  • Does anyone know how to use pages so you can export pdfs from the internet and automatically drag words from the document into the file name of the pdf (i.e., author, title of a scientific paper)

    Does anyone know how to use pages so you can export pdfs from the internet and automatically drag words from the document into the file name of the pdf (i.e., author, title of a scientific paper). For example, if I am downloading a paper by smith called "Surgery" that was published in 2002, it will automatically set the file name in the download to smith- surgery 2002. I have heard pages is smart enough to do this.
    thank you

    Pages can export only its own documents. They may be exported as PDF, MS Word, RTF or Text files.
    Pages can import (ie. Open a file as, or Insert a file into, a Pages document) documents in several formats, but won't rename the document as you describe. Documents that can be Opened (eg. Text, AppleWorks 6 WP, MS Word files) are converted to Pages documents, and retain their original names, with .pages replacing the original file extension. Files that can be Inserted (generally .jpg, .pdf and other image files) become part of the existing Pages file and lose their names.
    It may be possible, using AppleScript, to extract the text you want and to Save a Pages file using that text as the filename, but that would depend in part on being able to identify which text is wanted and which is not.
    How will the script determine where the author's name begins and where it ends?
    How will the script recognize the beginning and of the title, an decide how much of the title to use in the filename?
    How will the script recognize the year of publication?
    For papers published in a specific journal, with a strict format for placing each of these pieces on information, or containing the needed information as searchable meta data in the file, this might be possible. But it would require knowledge of the structure of these files, and would probably handle only papers published in a specific journal or set of journals.
    Outside my field of knowledge, but there are some talented scripters around here who might want to take a closer look.
    Best of luck.
    Regards,
    Barry

  • Can someone please tell me on how to modify this code so that I dont have to enter the file name at all?

    Hello
    can someone please tell me how to modify this code so that I dont have to enter the file path at all? When i give the same file path constants to both the read and write VIs I'm getting an error message.
    Attachments:
    read and write.vi ‏11 KB

    Yup use the low level File I/O opening the reference once, and closing it once.  
    As for the path selection you have an unwired input which is the path to use.  Programatically set that and you won't be prompted to select a path.  Usually this is done with a path constant to a folder, then using the Build Path, to set the file name in that folder.
    Unofficial Forum Rules and Guidelines - Hooovahh - LabVIEW Overlord
    If 10 out of 10 experts in any field say something is bad, you should probably take their opinion seriously.

  • Changing the setting name in the file name

    How do I change en masse the file name in a compressor batch?. Say, instead of having the default codec name, IE "Apple Pro Res," I could choose something unique for myself.
    Or how do I just get rid of it the setting tag without using a custom destination?
    Studio X wrote:
    "You can permanently solve the issue by making a simple change in the Preset.
    Click on your preset to load it into the Inspector in Compressor
    Click on the "actions" icon underneath the Names & Descriptions fields.
    Go down to Default Destinations and set it to " Source w:o additional names"
    Save the preset.
    Now every time you apply the preset you'll get the file placed back into the source folder without the additional info in the file name.
    One caveat - make sure that your new file name does not exactly match (including the suffix) the original file. If it does, you'll overwrite the original.
    x"
    However I did not find this "w:o additional names" option.
    I am running Compressor V 3.5.3 - is that the reason?
    Cheers,
    Edwin

    Could be a version thing.
    In 3.5.3 it works like this:
    You first need to create a new Destination:
    In compressor select the Destination Tab (1), then press the PLUS sign (2).
    Select Local (if it's going to be on your computer) or Remote (if it's on a network)
    Compressor will ask you which folder. In this example I created a new folder, called 'testingfolder' (3).
    In the Inspector then you can choose the naming options. Which is now right by default (4). So you don't have to alter that.
    Now do all steps as Studio X described, but a slightly different:
    "You can permanently solve the issue by making a simple change in the Preset.
    Click on your preset to load it into the Inspector in Compressor
    Click on the "actions" icon underneath the Names & Descriptions fields.
    Go down to Default Destinations and set it to " Source w:o additional names"
    ...set it to 'testingfolder'
    Save the preset.
    Now every time you apply the preset you'll get the file placed back into the source folder without the additional info in the file name.
    One caveat - make sure that your new file name does not exactly match (including the suffix) the original file. If it does, you'll overwrite the original.
    [The latter is only true if the destination folder is the same as the source folder, which I'd strongly advise not to do.]
    Rienk

  • Setting Up The Way Tags Appear in the File Name

    My original filename: Guns N Roses - Live and Let Die.mp3
    After dragging this (and hundreds more) into iTunes,
    the file name now appears as: 10 Live and Let Die.mp3
    I have since unchecked the 'Keep iTunes Media folder organized', which I now know is the reason my files names have changed, BUT - it's too late for all those songs I added, since iTunes sucked them right in without leaving me my originals.
    How can I get my original copies back to their original file names? I prefer the artist's name first, rather than the track number. Some 'automatic' way...not renaming them manually one by one, which would take all year long.
    How d'ya like them Apples,
    Zoletta

    Hi, welcome to Apple Discussions.
    Try http://dougscripts.com/itunes/scripts/ss.php?sp=appendartisttofilename - and if that doesn't quite do what you want there should be something else there that will...
    tt2

  • Save as window size keeps going back to the default size. I need it to stay the size I set it at so I can read the end of the file name.

    .When I save a file in Photoshop, I save for web and devices. It gives you the first window which I always just hit enter. Then it gives you a second window to name the file and where to put it. The problem I’m having is that’s it’s not remembering I want the window bigger and I can’t see the whole name of the file. I need to see the end of the file name so I know what to save the next file as. I can scroll or make the window bigger again but that is too time consuming when I’m trying to do hundreds of them a day.
    I'm using Photoshop CS4 on a Mac running Yosemite.

    BOILERPLATE TEXT:
    Note that because this is boilerplate text, not all points may apply to any given, specific poster.
    If you give complete and detailed information about your setup and the issue at hand,
    such as your platform (Mac or Win),
    exact versions of your OS, of Photoshop (not just "CS6", but something like CS6v.13.0.6) and of Bridge,
    your settings in Photoshop > Preference > Performance
    the type of file you were working on,
    machine specs, such as total installed RAM, scratch file HDs, total available HD space, video card specs, including total VRAM installed,
    what troubleshooting steps you have taken so far,
    what error message(s) you receive,
    if having issues opening raw files also the exact camera make and model that generated them,
    if you're having printing issues, indicate the exact make and model of your printer, paper size, image dimensions in pixels (so many pixels wide by so many pixels high). if going through a RIP, specify that too.
    etc.,
    someone may be able to help you (not necessarily this poster).
    a screen shot of your settings or of the image could be very helpful too.
    Please read this FAQ for advice on how to ask your questions correctly for quicker and better answers:
    http://forums.adobe.com/thread/419981?tstart=0
    Thanks!

  • The File name property is not valid. The file name is a device or contains invalid characters

    I have an SSIS task that has run successfully for years. They just moved the dtsx to a new server and now it is failing. 
    Issue:
    The task has a data flow that writes a raw file destination. It then has a subsequent data flow that reads the raw file destination. 
    The path and name of the raw file is passed to each of the data flows via the same variable. 
    The raw file resides in a folder on the server in the same path that the dtsx resides in. 
    The task fails with the "The File name property is not valid. The file name is a device or contains invalid characters" error when trying to access the raw file.
    What we have done to troubleshoot:
    1. I ran the task successfully on my local machine so it is definitely a server issue.
    2. The first thing we were seeing was that it failed trying to write to the raw file. The task is set to "Create Always". 
    3. We saw that the dba's copied over the entire directory structure from the old server which included a previously created raw file, so we deleted the raw file.
    4. We reran the task and it successfully wrote a new raw file but then failed on reading the raw file with the same error as above.
    5. We reran the task AGAIN and this time it failed trying to write the raw file throwing the same error as above.
    6. The dba looked at the directory and the account that performs the task has full control.
    7. The dba looked at the raw file that was created and verified that the account that performs the task has full control of the file and that it is the owner of the file.
    Summary:
    The task fails when trying to access the file EXCEPT when the file does not exist. In that situation it can write the file but subsequently fails in accessing it again.

    Hi Whalensdad,
    Based on my research, the issue can be caused by the following reasons:
    There are some invalid characters in the File name at package runtime. In this scenario, just as Russ said, could you please post the value that is in the File name variable? Also use a Script Task with Messagebox.show to show the variable values at runtime.
    May be it changes to others at run time.
    The account runs the package not having access to all the folders in the path. Since you are moving the dtsx file from one server to the current server, do you also move the raw file to the same folder in the current server? Does the user runs the package
    have access to all the folders in the path? To solve this, please ensure that the user has access to all folders and the raw file in the path on the current server.
    Thanks,
    Katherine Xiong
    If you have any feedback on our support, please click
    here.
    Katherine Xiong
    TechNet Community Support
    Please see the response above. I can't use a message box on a server so I logged the values to the database. The resource account has full control to the folder. I haven't been able to get the DBA to check the SQL Agents permissions, but I was always under
    the impression that if you use "Run As" on the task, it will not use the SQL Agent but the account you identify it to "Run As". The "Run As" account has full control on the folder and file.

  • Changing the File Name

    Hi
    i am designing a adobe form which will be send in mail when a button is clicked, i found that the attachment name to be "unknown.pdf". how can i change this ???
    i found out a method called getAcrobatApplicationName() in XML and when i changed application name in that its not getting reflected. So is there any other way to change the file name on "Button Click" event?
    Thanks
    Gopal

    Hi Gopal,
    See if it helps:
    In NW2004s we use the following. getPdf() returns a byte[], the filename is "document-<username>.pdf" and source is the attribute of an IFrame UI element.
    code
    private void initPdf() {
    IWDResource resource =
    WDResourceFactory.createResource(
    getPdf(),
    "document-"
    + WDClientUser.getLoggedInClientUser().getSAPUser().getUniqueName(),
    WDWebResourceType.PDF);
    String source =
    resource.getUrl(WDFileDownloadBehaviour.OPEN_INPLACE.ordinal());
    wdContext.currentContextElement().setSource(source);
    [/code]
    On NW2004 we use a FileDownload UI element (with target=_self) and we call initFileBinaryType method in the wdDoInit method. Of course you still need to set the binary PdfData context attribute with the actual content of the PDF file.
    code
    private void initFileBinaryType() {
    IWDModifiableBinaryType pdf =
    initFileBinaryType(IPrivateTestAppView.IContextElement.PDF_DATA);
    pdf.setFileName("document-"
    + WDClientUser.getLoggedInClientUser().getSAPUser().getUniqueName());
    pdf.setMimeType(WDWebResourceType.PDF);
    private IWDModifiableBinaryType initFileBinaryType(String attribute) {
    return (IWDModifiableBinaryType) wdContext
    .getNodeInfo()
    .getAttribute(attribute)
    .getModifiableSimpleType();
    [/code]
    Regards,
    Arafat

  • Sender File adpater to Pick Two files at a time based on the file name

    Hi Everyone,
    I have a scenario where I need to pick two files at a time using file adapter where the two files names have a common string in between their names.For example , the file names can be sets like
    H123.txt and L123.txt
    H345.txt and L345.txt.
    Now how do we handle this in the File Adapter ?

    Anu,
    Two approaches.
    1.     Use BPM: use a collect pattern to pick those files: L and H files , use multi mapping to merge those files and map to IDoc. Constraint is that there must be a mandatory correlation field in both the files. Say a same po id  in L and H file.
    2.     Use an Adapter module with additional files option in file Adapter. Operate on the Main payload and attachment inside your module code to get a combined contents of both files and proceed.
    Module is preferable in terms of performance, but maintenance is difficult. Deployment after each changes, transport issues, etc.
    BPM is resource intensive, but easy to maintain, transport.
    Choose based on your requirement.
    Regards,
    Sudharshan N A

Maybe you are looking for

  • SID in Update Table of DSO

    Hi, What is the use of the SID in the update (or new) table of DSO? Anyway the values of the data and key fields are stored in this table. How does the SID entry help here? Regards,

  • Volume don´t appear in MDC

    Hello, I have 2 servers with xsan 2.1.1 with Mac Os 10.5.6 Server, and I created four volumes in xsan2, and one of them dont saw in one of the servers. The log says: Jul 28 13:14:18: --- last message repeated 1 time --- Jul 28 13:14:18 xsand[49]: mkd

  • Can I purchase an unlocked iPhone in the US and use it in Malta?

    Hi all I'll be visiting NYC in the coming months and I would love to own an iPhone 4s! I am interested in buying an unlocked iPhone 4s from an authorised Apple store in NYC as the current prices in my country, Malta for an iPhone 4s is $800 with one

  • How to read a .wav file from a .jar  - Please Help!!!

    Hello, I know this is a stupid question but I keep having trouble doing this. My code is the following:     Display display;     Alert alert;     InputStream stream;     Player player; stream = getClass().getResourceAsStream("newalert.wav");         

  • Battery low!?

    I've just been on holiday, and took my mini iPod with me, and my speakers. During the holiday, I noticed that the battery life shortened considerably each day, even though I had it on charge all night each night. Now, a week after I got back home, th