[Original] Flex + Struts2 File Download Control

2010-05-01  来源:本站原创  分类:Flash  人气:314 

<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="334" height="140" fontSize="12" title=" File download  " creationComplete="init();">
        <mx:states>
                <mx:State name="Failure">
                        <mx:AddChild relativeTo="{FinishBtn}" position="before">
                                <mx:Button label=" Try again  " click="onRetry();"/>
                        </mx:AddChild>
                </mx:State>
        </mx:states>
        <mx:Script>
                <![CDATA[
                        import mx.managers.PopUpManager;
                        import mx.controls.Alert;
                        import flash.net.FileReference;
                        import flash.net.URLRequest;
                        import flash.events.ProgressEvent;

                        private var request:URLRequest;
                        private var _fileRef:FileReference;
                        private var _fileName:String;
                        private var _url:String;
                        private static const ROOT_URL:String="http://127.0.0.1:8080/TEST/";

                        private function init():void {
                                PopUpManager.centerPopUp(this);
                        }

                        public function set downUrl(uploadUrl:String):void {
                                _url=ROOT_URL + uploadUrl + ".action";
                        }

                        public function set fileName(fileName:String):void {
                                _fileName=fileName;
                        }

                        public function download():void {
                                Security.allowDomain("*");
                                _fileRef=new FileReference();
                                _fileRef.addEventListener(Event.COMPLETE, onComplete);
                                _fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
                                _fileRef.addEventListener(Event.CANCEL,onClose);
                                try {
                                        request=new URLRequest(_url);
                                        _fileRef.download(request, _fileName);
                                } catch (illegalOperation:IllegalOperationError) {
                                        trace('IllegalOperationError');
                                        onError();
                                } catch (security:SecurityError) {
                                        trace('SecurityError');
                                        onError();
                                }
                        }

                        private function onClose(evt:Event):void{
                                close(false);
                        }

                        private function onComplete(evt:Event):void {
                                this.currentState = '';
                                fileInfo.text=" File  :" + _fileName + " Download the complete  !";
                                FinishBtn.label=" Complete  ";
                        }

//                       Progress bar
                        private function onProgress(evt:ProgressEvent):void {
                                var loaded:uint = evt.bytesLoaded;
                                var total:uint = evt.bytesTotal;
                                fileInfo.text=" File  :" + _fileName + "  Size  :" + formatFileSize(total);
                                var proc:uint=loaded / total * 100;
                                pbar.setProgress(proc,100);
                                pbar.label=" Current progress  :" + proc + "%";
                        }

                        private function onError():void {
                                Alert.show(' File upload fails, check your network connection  !', ' Error  ', Alert.OK, null, function():void {
                                                this.currentState = 'Failure';
                                                fileInfo.text=" File  :" + _fileName + " Download fails, check network status  !";
                                });
                        }

                        private function onCancel():void {
                                _fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);
                                _fileRef.removeEventListener(Event.COMPLETE, onComplete);
                                _fileRef.cancel();
                        }

                        private function formatFileSize(size:Number):String {
                                if ((1024 * 1024 * 1024) <= size) {
                                        return Math.round(size / (1024 * 1024 * 1024)) + "GB";
                                } else if ((1024 * 1024) <= size) {
                                        return Math.round(size / (1024 * 1024)) + "MB";
                                } else if (1024 <= size) {
                                        return Math.round(size / 1024) + "KB";
                                } else {
                                        return size + "B";
                                }
                        }

                        private function close(flag:Boolean):void {
                                if (flag) {
                                        try {
                                                onCancel();
                                        } catch (error:Error) {
                                                trace("ERROR");
                                        }
                                }
                                PopUpManager.removePopUp(this);
                        }

                        private function onRetry():void{
                                try {
                                        _fileRef.download(request, _fileName);
                                } catch (illegalOperation:IllegalOperationError) {
                                        trace('IllegalOperationError');
                                        onError();
                                } catch (security:SecurityError) {
                                        trace('SecurityError');
                                        onError();
                                }
                        }
                ]]>
        </mx:Script>
        <mx:VBox height="100%" width="100%">
                <mx:Label width="100%"/>
                <mx:ProgressBar labelPlacement="center" minimum="0" maximum="100" label=" Download progress  : 0%" direction="right" mode="manual" width="100%"/>
                <mx:HBox width="100%" verticalAlign="middle" horizontalAlign="center">
                        <mx:Button label=" Termination  " click="close(true);"/>
                </mx:HBox>
        </mx:VBox>
</mx:TitleWindow>
/**
 *
 */
package com.io.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.ajax.base.action.BaseAction;

/**
 * @author Merrygrass  2010-4-20
 *
 */
@SuppressWarnings("serial")
public class DownloadAction extends BaseAction {
        private String contentType;
        private String fileName;
        private InputStream inputStream;
        private String contentLength;

        public String download(){
                return "download";
        }

        public String getContentType() {
                return contentType;
        }

        public void setContentType(String contentType) {
                this.contentType = contentType;
        }

        public String getFilename() {
                try {
                        fileName = "1005011041035572.flv";
                        fileName = new String(fileName.getBytes(),"ISO8859-1");
                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                }
                return fileName;
        }

        public void setFileName(String fileName) {
                this.fileName = fileName;
        }

        @SuppressWarnings("deprecation")
        public InputStream getInputStream() throws Exception {
                String realPath = ServletActionContext.getRequest().getRealPath("/upload");
                File file = new File(realPath + "/" + "1005011041035572.flv");
                if(file.exists()){
                        contentLength = String.valueOf(file.length());
                }else{
                        throw new Exception(" The file does not exist  !");
                }
                inputStream = new FileInputStream(realPath + "/" + "1005011041035572.flv");
                return inputStream;
        }

        public void setInputStream(InputStream inputStream) {
                this.inputStream = inputStream;
        }

        public String getContentLength() {
                return contentLength;
        }
}
<action name="downloadAction">
   <result name="download" type="stream">
    <param name="contentType">application/octet-stream;charset=ISO8859-1</param>
    <param name="inputName">inputStream</param>
    <param name="contentDisposition">attachment;filename="${fileName}"</param>
    <param name="bufferSize">4096</param>
    <param name="contentLength">${contentLength}</param>
   </result>
     </action>
相关文章
  • [Original] Flex + Struts2 File Download Control 2010-05-01

    <?xml version="1.0" encoding="utf-8"?> <mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="334" height="140" fontSize="12" title=" File down

  • struts2 file download occurs java.lang.IllegalStateException 2010-10-21

    Let us talk about the background of program design, function is to achieve file downloads, ideas, Mr. Cheng is a temporary file, download to delete the temporary files. Here again I use struts2. First thought is normal configuration directly deal wit

  • struts2 file download error solution 2011-05-23

    1. Jsp page hyperlinks <a href="javascript:void(0)" "downloadFile('${id}')"> $ {name} </ a> 2. Form submission <form action="downloadFile.html" method="post" enctype="multipart/form-data" ta

  • Struts2 file download section Baocuo, can not find input stream 2010-03-29

    tomcat Baocuo are as follows: Seriously: Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack. Check the <param name="inputName"> tag specified for this action. This error usually occurs only two possibil

  • File download internet Explorer can not download solution 2010-12-08

    We used to do such a framework similar to struts2 file download, they would often pop up a box, suggesting that internet Explorer can not download the case, in which case, more is the file name is Chinese, so we want to transcode the file name <resul

  • struts2 file upload and download 2010-11-13

    Successful re-upload the modified page to support the contents of the file download code. ? DownloadAction file download feature development. ? Struts.xml in DownloadAction configuration and support files to download a file called Chinese characters.

  • struts2 stream file download action with the Thunder when the file suffix 2010-06-24

    Using struts2 write Streaming file download , For example, export excle file , Use the Windows file save as , No problem, but when using Peter , Download the file suffix .action. Address: ideas, Thunder download get the name of the requested action.

  • flex (AIR) Remote File Download examples (ultimate edition) 2010-11-16

    <? Xml version = "1.0" encoding = "utf-8"?> <S: WindowedApplication xmlns: fx = "http://ns.adobe.com/mxml/2009" xmlns: s = "library: / / ns.adobe.com / flex / spark" xmlns: mx = "library: / / ns.adobe.

  • nginx X-Accel-Redirect for file download rails devise and implement access control 2011-03-14

    Question 1: Nginx's X-Accel-Redirect? A: Download the file permissions for the precise control needed in many places, such as a paid download service, network drives, personal album, the contents of this site is outside the station to prevent hotlink

  • Flex + Struts2 + JSON and background to achieve Flex HTTP Service request 2010-03-28

    Flex + Struts2 + JSON code in the background which I say no more. See I do not know how to write an article on "Struts2 + JQuery + JSON Asynchronous interaction," the article, the background has not changed. In this talk focused on the realizati

  • Flex + Struts2 + JSON submitted to the Ministry to achieve different 2010-04-22

    Flex + Struts2 + JSON code in the background which I say no more. See I do not know how to write an article on "Struts2 + JQuery + JSON Asynchronous interaction," the article, the background has not changed. In this talk focused on the realizati

  • Struts 2 in the implementation file download (amended the Chinese problem) 2011-01-11

    Struts 2 in the implementation file download (amended the Chinese problem) In BlogJava already has a file upload of the problems described, the address is implemented in Struts 2 File upload , so I will not discuss that topic. Today, I briefly talk a

  • Flex upload and download 2011-04-27

    In the project development process, often encounter problems uploading and downloading files. However, due to security sandbox flex reasons, flex can not directly access local files. But the flex SDK provides a FileReference and FileReferenceList in

  • Java HTTP file download software of resources 2010-03-29

    First, HTTP principle <? XML: NAMESPACE PREFIX = O /> The so-called HTTP, the popular thing is that files have been downloaded from the start where to download. Said accurate point is that HTTP Zhi download or upload will be downloaded or upload Ren

  • Flex + Struts2 upload multiple files can not be achieved 2010-10-28

    The Internet to find a Flex multiple file upload component, I wrote it myself as the Servlet server, can upload, but for using Struts2, you can not upload, what is the reason. . . I fast two days torture! Please help me brothers! Thank you!

  • java Struts2 interceptor access control using the example of 2010-12-24

    Struts2 interceptor access control using the examples of keywords: struts2 example of access control requirements: Require users to log in, and must specify the user name for the system can see a view of resources; Otherwise, the system directly to t

  • java implementation file download 2010-03-29

    1, using RequestDispatcher way 1, web.xml file to add <mime-mapping> <extension> doc </ extension> <mime-type> application / vnd.ms-word </ mime-type> </ mime-mapping> 2, the program is as follows: " % @ page langu

  • Java file download in several ways 2008-05-15

    Java file download in several ways public HttpServletResponse download(String path, HttpServletResponse response) { try { // path Refers to download the file path . File file = new File(path); // Get the file name . String filename = file.getName();

  • Solve Invalid white space character (0x - file download can be directly used 2010-03-24

    Making soa webservice development, you may encounter an error message similar to the following: com.ctc.wstx.sw.BaseStreamWriter.writeCharacters (BaseStreamWriter.java: 509) Invalid white space character (0x1) in text to output Invalid white space ch

  • The non-ajax request returns json, xml data file download prompts that appear 2010-03-05

    The non-ajax requests are returned in the Action json or xml data file download prompt will appear xx.do box.