upload a zip file using HTTP POST via actionscript

2020-04-16 18:43发布

问题:

I have a zip file that is created using drag and drop on a view in my desktop Flex 4.6 app.

This triggers a service that will automatically upload the zip file.

I am able to use the following code to send metadata about the zip file to the server.

        var urlRequest:URLRequest = new URLRequest(PUBLISH_ZIP_FILE_URL);
        // set to method=POST
        urlRequest.method = URLRequestMethod.POST;          



        var params:URLVariables = new URLVariables();



        params['data[File][title]'] = 'Title1';
        params['data[File][description]'] = 'desc';         
        // params['data[File][filename]'] =  I am not sure exactly what to use here 
        // If this is a webpage, I expect to use input type="file" with the name as data[File][filename]


        urlRequest.data = params;

        addLoaderListeners();

        // set it such that data format is in variables
        loader.dataFormat = URLLoaderDataFormat.VARIABLES;

        loader.load(urlRequest);

I have read https://stackoverflow.com/questions/8837619/using-http-post-to-upload-a-file-to-a-website

However, immediately they start off with ByteArray, which I am not sure how to convert my zip file at all.

Please advise.

回答1:

Embarrassing but I found my answer 42 mins after I posted the question.

A little bit of a rubber duck problem solving going on here.

http://www.codinghorror.com/blog/2012/03/rubber-duck-problem-solving.html

Short answer: Use File class and specifically the method upload which is extended from the FileReference class.

Long answer:

        var urlRequest:URLRequest = new URLRequest(PUBLISH_ZIP_FILE_URL);
        // set to method=POST
        urlRequest.method = URLRequestMethod.POST;

        var params:URLVariables = new URLVariables();

        params['data[File][title]'] = 'Title1';
        params['data[File][description]'] = 'desc';

        // this is where we include those non file params and data
        urlRequest.data = params;


        // now we upload the file
        // this is how we set the form field expected for the file upload
        file.upload(urlRequest, "data[File][filename]");