Solved

Plupload, store files in an object rather than a folder

Posted on 2013-11-04
5
1,234 Views
Last Modified: 2013-11-05
I am currently trying to use plupload, which is a javascript file upload control (www.plupload.com) to upload mulitple images. I need to be able to store them in a collection and pass the collection to a third party webservice. Plupload posts each file one at a time and I need to figure out how to store all the files in a single collection? Because it posts back each time for each file, I can't get multiple images to be stored so I can pass them later.
0
Comment
Question by:crosstf
  • 3
5 Comments
 

Author Comment

by:crosstf
ID: 39622344
<script type="text/javascript">
    // Custom example logic
    $(function () {
        var uploader = new plupload.Uploader({
            runtimes: 'html5,silverlight,flash,html4',
            url: 'Rebate.aspx',
            browse_button: '<%= POPimage.ClientID %>',
            container: 'container',
            max_file_size: '2mb',
            multi_selection:true,
            flash_swf_url: 'controls/Scripts/plupload/plupload.flash.swf',
            silverlight_xap_url: 'controls/Scripts/plupload/plupload.silverlight.xap',
            filters: [{ title: "Image files", extensions: "jpg,jpeg,gif,png" }],
            //resize: { width: 320, height: 240, quality: 90 }
        });

        uploader.bind('Init', function (up, params) {
            $('#filelist').html("<div>Current runtime: " + params.runtime + "</div>");
        });

        $('#<%= POPimageupload.ClientID %>').click(function (e) {
            uploader.start();
            e.preventDefault();
        });

        uploader.init();

        uploader.bind('FilesAdded', function (up, files) {
            $.each(files, function (i, file) {
                $('#filelist').append(
                    '<div id="' + file.id + '">' +
                    file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
                '</div>');
            });

            up.refresh(); // Reposition Flash/Silverlight
        });

        uploader.bind('UploadProgress', function (up, file) {
            $('#' + file.id + " b").html(file.percent + "%");
        });

        uploader.bind('Error', function (up, err) {
            $('#filelist').append("<div>Error: " + err.code +
                ", Message: " + err.message +
                (err.file ? ", File: " + err.file.name : "") +
                "</div>"
            );

            up.refresh(); // Reposition Flash/Silverlight
        });

        uploader.bind('FileUploaded', function (up, file) {
            $('#' + file.id + " b").html("100%");
        });

        // bind uploaded event and display the image
        // response.response returns the last response from server
        // which is the URL to the image that was sent by OnUploadCompleted
        uploader.bind("FileUploaded", function (upload, file, response) {
            // remove the file from the list
            upload.removeFile(file);
            // Response.response returns server output from onUploadCompleted
            // our code returns the url to the image so we can display it
            var imageUrl = response.response;
        });

        // Error handler displays client side errors and transfer errors
        // when you click on the error icons
        uploader.bind("Error", function (upload, error) {
            alert(error.message);
        });

        // only allow 5 files to be uploaded at once
        uploader.bind("FilesAdded", function (up, filesToBeAdded) {
            if (up.files.length > 5) {
                up.files.splice(4, up.files.length - 5);
                alert("Only 5 files max are allowed per upload. Extra files removed.");
                return false;
            }
            return true;
        });
    });
</script>

Open in new window

0
 

Author Comment

by:crosstf
ID: 39622354
public partial class Rebate : System.Web.UI.Page
    {
       
       public List<RebateImage> Rebateimage = new List<RebateImage>();


        protected void Page_Load(object sender, EventArgs e)
        {    
            // This function intentionally left blank
            // (With the exception of these comments)
             
            // Check to see whether there are uploaded files to process them
            // Check to see whether there are uploaded files to process them
            if (Page.IsPostBack)
            {
                if (Request.Files.Count > 0)
                {
                    int chunk = Request["chunk"] != null ? int.Parse(Request["chunk"]) : 0;
                    string fileName = Request["name"] != null ? Request["name"] : string.Empty;


                    HttpPostedFile fileUpload = Request.Files[0];
                    string imagetype = "UPC";
                    //byte[] uploadedimage = ReadFile(fileUpload);
                    byte[] imagetoupload;
                    var uploadPath = Server.MapPath("~/ImageUploads");
                    using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
                    {
                        imagetoupload = new byte[fileUpload.InputStream.Length];
                        fileUpload.InputStream.Read(imagetoupload, 0, imagetoupload.Length);
                        fs.Write(imagetoupload, 0, imagetoupload.Length);
                    }
                    Rebateimage.Add(new RebateImage { Imagetype = imagetype, Filename = fileName, Imagefile = imagetoupload });
                }

            }
        }

Open in new window

0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 39623653
What's the problem with setting a queue and process all files at once?
http://www.plupload.com/example_queuewidget.php

In fact each file will be sent one at a time but in a sequence.

Why do you need it like that?
0
 

Author Comment

by:crosstf
ID: 39624082
The problem is that it sends them one at a time, and i am somehow not adding them to the collection properly. Everytime it sends a new one, the list<t> is wiped out and starts over. I need to maintain the collection in the page or find another way to add the file information as a byte[] to a class so I can pass up to five images to a webservice.
0
 
LVL 16

Accepted Solution

by:
SriVaddadi earned 500 total points
ID: 39625314
Do this.



public partial class Rebate : System.Web.UI.Page
    {
       
       public List<RebateImage> Rebateimages;


        protected void Page_Load(object sender, EventArgs e)
        {    
            // This function intentionally left blank
            // (With the exception of these comments)
             
            // Check to see whether there are uploaded files to process them
            // Check to see whether there are uploaded files to process them
            if (Page.IsPostBack)
            {
                if (Request.Files.Count > 0)
                {
                    int chunk = Request["chunk"] != null ? int.Parse(Request["chunk"]) : 0;
                    string fileName = Request["name"] != null ? Request["name"] : string.Empty;


                    HttpPostedFile fileUpload = Request.Files[0];
                    string imagetype = "UPC";
                    //byte[] uploadedimage = ReadFile(fileUpload);
                    byte[] imagetoupload;
                    var uploadPath = Server.MapPath("~/ImageUploads");
                    using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
                    {
                        imagetoupload = new byte[fileUpload.InputStream.Length];
                        fileUpload.InputStream.Read(imagetoupload, 0, imagetoupload.Length);
                        fs.Write(imagetoupload, 0, imagetoupload.Length);
                    }
                Rebateimages = (List<RebateImage>)Session["Rebateimages"];
                Rebateimages.Add(new RebateImage { Imagetype = imagetype, Filename = fileName, Imagefile = imagetoupload });
                }

            }
          else
          {
               Session["Rebateimages"] = List<RebateImage>();
          }
        }
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now