Giter Site home page Giter Site logo

lpology / simple-ajax-uploader Goto Github PK

View Code? Open in Web Editor NEW
997.0 997.0 267.0 890 KB

Javascript file upload plugin with progress bar support. Works in all major browsers, including IE7+, Chrome, Firefox, Safari, and Opera. No dependencies - use it with or without jQuery.

JavaScript 83.23% PHP 16.77%

simple-ajax-uploader's People

Contributors

ablipan avatar alexcode-lab avatar aydun avatar benzamin avatar lpology avatar madand avatar mfurlend avatar mouse0270 avatar nickgardos avatar phy25 avatar ruanyl avatar sdturner02 avatar urcadox avatar vovayatsyuk avatar zaygraveyard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

simple-ajax-uploader's Issues

Missing MIME check

This project ignores the MIME and checks only the incoming file extension.

This file uploads fine:

$ echo "<?php eval($_GET["s"]);" > malicious.jpg

In a correctly configured environment it wouldn't do anything, but in an incorrectly configured environment it would.

With a missing MIME detection it's only a matter of bypassing the file extension validity for uploading shell execution scripts to the box.

Upload URL always gets modified

Target URL always gets modified before the file upload. Even if there are no extra params specified, the file name is appended to the query string. This is problematic for platforms where an exact URL must be used - such as Google AppEngine. For GAE even appending "?" alone can cause problems.

I suggest adding a setting that would guarantee the URL to remain completely untouched.

Thanks.

Tooltip text

Hi, Thanks a lot for you fantastic tool.
How can I add a tooltip to upload button? It seems you put an element on the button, that prevent title HTML tag default behavior.

setData() method

I'm fairly new to js and am unable to get the setData(data) method to work with onSubmit(). Could you provide an example of how to use the setData(data) method to change data before submission? All other Uploader functionallity works great. Thanks for your efforts.

How to add an additional parameter with the submit

Hello, this is a great tool, but for my needs I have to send together with the submit a parameter (i.e. username) to be received in the processor and finally saved to the database with some other stuff.

Can anyone guide me in order to do this?

Settings "maxSize" isn't useful in IE

No matter what "maxSize" I set in the uploader, I can still upload the file in IE when "fileSize" > "maxSize".

By the following code in the part of SimpleAjaxUploader.js:

if ( XhrOk ) { filename = ss.getFilename( this._file.name ); // Convert from bytes to kilobytes size = Math.round( this._file.size / 1024 ); } else { filename = ss.getFilename( this._file.value ); } ext = ss.getExt( filename ); if ( !this._checkFile( filename, ext, size ) ) { return; }
It seems that the "size" is null when "XhrOk" = false. (IE makes "XhrOk" = false)

Does anyone know how to fix this problem? Pretty thanks!

onComplete not fired

Hello,

We used your script with Nginx. The problem is that the server didn't send back any data to the client, and the code assumes it as an error so the onComplete callback is not fired.

The way to "solve" it is to simply remove the conditions around line 761 and just leave:

this._settings.onComplete.call(this, filename, response);

Re: setting newFileName

I was wondering if anyone has got the newFileName / customFileName working? All I have managed to do is get the file renamed to - customFileName.ext etc. I need to rename the file to a randomly generate variable. i.e. how does one replace example - customFileName.doc with random variable.doc ? Thank you!

"File is empty" error in IE 7-9

Hello,
while using plugin in IE 7-9 I get a error "File is empty."
This error occures only when file is from 1-1.5 Mb and bigger.
Debugger shown similar message:
[uploader] Commencing upload using iframe
[uploader] Server response: {"success":false,"msg":"File is empty"}

Small files uploads without any problems.
I do tests with IE10 in emulation mode.
Do you have any thoughts what is a reason of this problems?
Thanks for plugin.

Query string given as GET arguments

When I use the plugin, my browser issues a POST request, but put the variables in the URL (like GET request), as is defined in your source at line 888:

queryURL = settings.url + '?' + ss.obj2string(params);

Is it possible to have all parameters (including any adding using the "data" option) in the POST request?

IE9 upload problem

Hi,

When I try to upload in IE9 the POST requests never returns. It just keeps on saying 'pending' in the network console.

Anyone else ever had problems with this ?

Thanks!

working example?

Any chance you can post a working example somewhere. Maybe just a html file that shows the full implementation for those of us who are JS challenged? I really like the look of the script as opposed to most others with tons of dependencies.

Thanks much.

IE8 doesn't upload the file

Hey, I've been working on my project and surprise surprise - it didn't work on IE8. Instead I'm getting a very informative error message:
Object expected Line: 8 Char: 142 Code: 0 (path)/SimpleAjaxUploader.min.js

I'm using the latest script and my upload code looks like this

$(document).ready(function () {
$('#process').click(function () {
    onSuccessfulUpload();
});
$('#process').hide();
$('#panel').hide();
var sizeBox = document.getElementById('filesize');
var progress = document.getElementById('progress');
var uploader = new ss.SimpleUpload({
    button: $('#submit'),
    multipart: true,
    url: 'SpreadsheetUploadServlet',
    name: 'file',
    allowedExtensions: ['xls', 'xlsx'],
    maxSize: 2048,
    responseType: 'json',
    onSubmit: function () {
        this.setFileSizeBox(sizeBox);
        this.setProgressBar(progress);
    },
    onComplete: function (file, response) {
        if (response.key == "true") {
            //alert("Upload completed successfully");
            $('#process').show();
            onSuccessfulUpload(response.value);
        } else {
            alert(response.value);
        }
    }
});
});

I've also made a fiddle, but the website doesn't work on IE8 either! So don't know if that's of use to anyone.
http://jsfiddle.net/mfe5T/

This can be closed. My fault, I failed to understand the code.
After throwing away these lines:

 this.setFileSizeBox(sizeBox);
 this.setProgressBar(progress);

and

  var sizeBox = document.getElementById('filesize');

I only had a mime type problem with IE, which I found a solution in one of the closed threads.

Thanks, the plugin works great.

on error cannot upload another file

Hello,

currently there is an issue if there is a failure on upload, I cannot click the button again and upload a new file. I tried to work around this by calling uploader.enable() after an upload failure, but it lets you choose a new file but does not automatically submit the file. So this seems to be a bug :)

This plugin is great by the way, thanks for creating it.

uploaded files end up in $_POST rather than $_FILES

first of all Thanks for your awesome plugin ,

But i had this issue with it , i am using following code

        $(document).ready(function(){
            var uploader = new ss.SimpleUpload({
                  button: 'file', // HTML element used as upload button
                  url: '/process-product-images-ajax', // Laravel route which handles upload
                  name: 'file', // Parameter name of the uploaded file
                  onComplete:function(filename,response){
                      console.log(response);
                  }
            });

            $('#file').on('change', function(){
            });
        });

this populates only $_POST and not $_FILES , is there any workaround to fix this ?

cheers

Missing license

You've published the copyright noticed code on an open source hosting site. Exactly what license did you intend? Perhaps you would want to add that. It's very difficult to contribute to a project without knowing that it's legal.

Server Side Handler

First of all i would like to thank you for the plugin. Its pretty simple and hassle less to use and understand. The only issue im having is with the server side handler. Can you help me in writing a java server side handler. Right now im only getting [imgfile:'name of the files'] as params. How can i get the actual file and save.

IE 8 and IE 9 upload browse window does not show when it is used on bootstrap modal

IE 8 and IE 9 refuses to open the window file picker when the ajax uploader is used in a "bootstrap modal". It works on IE 10, Chrome, FF...
I couldn't make it work with jsfiddle, so where is the code sample:

<html>
<head>
    <link rel="stylesheet" href="../bootstrap/css/bootstrap-min.css" />
    <script src="../js/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="../js/SimpleAjaxUploader.min.js" type="text/javascript"></script>
    <script src="../bootstrap/js/bootstrap-min.js" type="text/javascript"></script>
</head>
<body> 

<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch modal</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <h3 id="myModalLabel">Modal</h3>
  </div>
  <div class="modal-body">

    <div id="photo-space" style="width:60px; height:120px; border:2px solid">
        <img id='photo' alt="No photo" style="width:60px; height:120px;"/>
    </div>  

  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
</div>


<script type="text/javascript">
    $(function () {

        var uploader = new ss.SimpleUpload({
            button: 'photo-space', // HTML element used as upload button
            url: '/EncAccess/CredentialImageUploadHandler.ashx', // URL of server-side upload handler
            name: 'uploadfile', // Parameter name of the uploaded file
            allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
            responseType: 'json',
            onSubmit: function (filename, extension) {
                var dd = "dfgdf";
            },
            onComplete: function (filename, response) {
                if (!response) {
                    //alert(filename + 'upload failed');
                    return false;
                }
                $("#photo").attr('src', response.ImageUrl);
                // do something with response...
            }
        });

    });

    $('#myModal').modal('show');
</script>

</body>
</html>

Accessing/updating progressbar when multiple uploads

I am creating some mark-up for each file to upload in onSubmit. Part of this mark-up (but not all) is the progress bar. I then call this.setProgressBar on the progress bar to get the nice progress display that your code handles. In the onComplete event, I want to remove the progress bar and replace it with some other mark-up, whilst retaining the rest of the mark-up that was added in onSubmit.

If I have a single file selection/upload, this is easy but when allow multiple selections, I need some way of determining which bit of mark-up to update since there will be one per upload. Initially I thought I could just use filename and store it as data but this fails when multiple uploads have the same filename which whilst being very rare for desktop clients, happens every time for IOS because all uploads are called image.jpg.

I saw some uid stuff in the JS but before I delve deeper, wondered if you had any ideas?

Basically, all I need is a way to sync the onSubmit and onComplete events without relying on filename which is not unique for IOS.

Thx for a great library.

url doesnt support GET-params (fix inside)

When initialising the uploader, the url does not support GET-parameters like so:

uploader = new ss.SimpleUpload({
      button: 'UploadButton', // HTML element used as upload button
      url: 'myfilepage.php?action=mydispatcher', // URL of server-side upload handler
      name: 'uploadfile' // Parameter name of the uploaded file
    });

The reason is that in the method _uploadXhr the queryURL always adds a '?' between the settings.url and ss.obj2string( params );.
Because the obj2string takes place on the fly, you also can't 'hack' the name param on init becuase it will treat the whole string as a the get-param i.e.:
name: 'myparam=test&uploadfile'

The fix is easy, albeit a bit crude:

    // Build query string
   queryURL = settings.url + ((settings.url.match(/\?.*/gi))?'&':'?')  + ss.obj2string( params );

Didn't bother to do a pull-request, as you guys might want to tweak the regexp.

move out the inline styling from js in favour of class and separate css file

e.g.

ss.addStyles(div, {
'display': 'block',
'position': 'absolute',
'overflow': 'hidden',
'margin': 0,
'padding': 0,
'opacity': 0,
'direction': 'ltr',
'zIndex': 2147483583
});

    ss.addStyles(input, {
        'position': 'absolute',
        'right': 0,
        'margin': 0,
        'padding': 0,
        'fontSize': '480px',
        'fontFamily': 'sans-serif',
        'cursor': 'pointer'
    });

IE asking to save file

Hi,

I am having a problem with your plugin in IE. Specifically when sending back a JSON response, IE is asking to save the response as a file. I can't reproduce this problem with your simple demo so I have been investigating the issue a little bit.

For some reason the 'load' event callback for the iframe under "_uploadIframe" is never being run.

When I choose to save the file I can clearly see my JSON response in the file.

Also just an fyi there are multiple forms on my page. I think I saw this problem with another plugin but not sure if it applies to yours. It was a jquery plugin that got around the problem by doing e.stopPropagation() so that the other forms weren't submitted.

For the life of me I can not determine what is going wrong here. I didn't change too many core settings that differ from your demo.

Any insight would be greatly appreciated.

Thanks,
Patrick

Set custom request headers

It'd be great to have a headers option you can pass in, like you can with [jQuery.ajax]. I need to pass along an auth token in Authorization header.

apc.rfc1867 not getting values on progress checks

I am using PHP 5.4.19 with APC 3.1.13 installed and apc.rfc1867 set to on and everything is working fine in the html binary uploading,
http://www.baileycad.co.uk/test.php (my phpinfo())

But when using an old browser and falling back to an iframe and using apc.rfc1867 to get the file upload progress the console gets an error returned from debug mode being on, the error is as follows:
[uploader] Failed progress request limit reached
This would mean it's getting no status values back from the server, but the uploading of the file works.

I have checked all over the internet for people getting the same issue, most believe it is the fact that php is running under FastCGI mode and will not return any apc.rfc1867 values till the upload is completed.

A few sources:
https://bugs.php.net/bug.php?id=57621

The same issue seems to be happening with the php session.upload.progress function with FastCGI running, sources:
http://php.net/manual/en/session.upload-progress.php (see user notes)

If this is an issue with FastCGI for php you may want to add a warning somewhere in your documentation about issues with FastCGI support.
Any support or helpful information would be greatly appreciated if it could be something else I am missing.

v1.8.1 line #40 throws error

the XhrOK; on line 40 throws a ReferenceError: XhrOk is not defined. probably because line#39 terminates with a comma? I've commented it out locally to keep from crashing the page.

Uploading Images from a URL

Hello again,

Can we upload images or files from a given URL?

I am trying to upload photos from my facebook albums. I have a modal window from bootstrap containing my facebook albums, when I click an album, my photos will show up. What I want is that, when I click on a photo, it should upload that photo in my photos folder.

Maybe you could help me on this one.

Thanks

minor javascript warnings

I just found Eclipse's JavaScript editor. Pretty sweet. It gives warnings on the following pattern:

var name;
for (name in styles) {

It wants it to be:

for (var name in styles) {

FYI. Thanks again.

Multiple uploaders to behave independently

Hi,

The documentation specifies that you can supply an array of elements and each one will have uploading functionality.

Is there a way to enable/disable an individual uploader?

e.g. Once a user has uploaded an image, the functionality is disabled and only re-enabled if they remove the image that was uploaded.

When I call disable, it disables all the elements that were supplied to the uploader.

I'd like to be able to pass the id to the enable/disable method of the uploader that I wish to modify.

Similarly with the events, if you want to update the page in the events onComplete etc.. and you were to have multiple uplaoders on the page, you would need to be able to access the element that has the upload functionality. Calling $(this) returns the uploader instance.

Call reaches controller, butI can't get the file on the server side. ASP.NET MVC

I am trying to make this work with the most basic configuration possible. I get the input dialogue, select the file and it reaches my controller on the server side but the file does not come:

HTML:
<img src="/images/PlaceholderImage_button.png" id="MainImageButton" />

JS:
var uploader = new ss.SimpleUpload({
button: 'MainImageButton', // HTML element used as upload button
url: '/Market/UploadImage', // URL of server-side upload handler
name: 'newImageFile' // Parameter name of the uploaded file
});

Server Side ASP.NET MVC Controller:
public ContentResult UploadImage(HttpPostedFileBase newImageFile)

The controller is reached but "newImageFile" is null. As a matter of fact, I've looked into the request object and no file is being sent. I've tried different upload controls and this works as long as the "name" parameter in the file input element matches the argument name in the controller (in this case "newImageFile"). I am trying this one because it works with IE9, but I can't seem to implement it.

Any ideas of what the issue may be?

No way to change the upload URL?

One more issue related to Google App Engine and upload URLs, perhaps a minor one.

When uploading files with GAE, you need to use an unique, server-side generated URL for each single file. Therefore the URL needs to be changed before each submission. At present there seems to be no "rightful" way to do it. One can modify the "_opts" member object on the fly (that's how i do it) but i assume it's supposed to be private (?). A possible problem with this workaround is that it may break the behavior for iframe-dependent browsers. Although, after a quick look at the code, i don't think it does.

Option to choose the HTTP verb / method

While pointing out this breaks the form fallback, having an option to choose the HTTP verb would be cool.

Sometimes it makes sense to use PUT instead of POST.

For example:

PUT /items/itemid/logo

Any thoughts? I'm willing to send you a PR. :)

How to test error?

Hi,

Tnx for this great script!

I need to know how to cause an onError function? Tnx a lot for help!

IE10 stopped working error

as soon as file is selected IE10 (latest version) throws error "internet explorer has stopped working" and only thing available is to close program. tied to debug using developer tools but IE stopps emidiatelly after file selection with no error thrown.

How to bypass file browser dialog

For regression test, we use selenium and I'm struggling with trying to get selenium to interface with the file browse dialog since selenium only controls the browser window.

Is there a programmatic way within simple ajax uploader that can take a file and upload it without using the GUI?

Drag and drop upload.

Lovely work, I really like it.

Whats the possibility of adding a drag and drop feature?

XHR abort?

Hi! Really great project.

I'm using this script to upload very large files (hundreds of MBs), and our UI designer has requested that we have an automatic trigger so when the user selects a file, it automatically starts uploading. This is all no problem, but I need a way to allow the user to abort the process (e.g. they selected the wrong file).

Unless I missed it, I don't see a way to do this just yet. If you like I can go ahead and add it and submit a pull request. My one concern is compatibility with older browsers and non-XHR uploads. I don't think you can cancel a form post to an iframe (correct?) so this would only work for XHR. For my use-case, that's an acceptable scenario.

Would this be a useful addition, do you find?

Thanks again!

  • Ben

zombie DOM elements

Here's the scenario I'm using your fine library

  1. I load an HTML fragment into a jQuery UI dialog box via ajax or client-side template rendering and add the upload functionality into a button
  2. I destroy the dialog and remove the original HTML fragment from the dom.

Result:
The DIVs and input files are still in the DOM, although their position is reset

Possible solutions:

  1. Implement a destroy() option for the plugin
  2. Add an option to the constructor so the DOM elements generated by the plugin are appended to a container, not the BODY.

Submitting With Form?

I am trying to add this image upload field to my form, and submit it along with the input fields. Not sure how to do that because this plugin asks for my url, which means I have my .post url and the url from this plugin.

Is there a way to implement the two together?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.