3

I am getting an internal server error 500 when I am uploading files with multiple other fields that I would like to use in the same method. However I can't seem to figure out what exactly is wrong. I am using Flask Upload in Python for this and I am not sure if I am missing something that is obvious. Below is the HTML, Javascript, and Python that I am using. Any help would be greatly appreciated.

<form method=POST enctype=multipart/form-data id="contentAddForm" class="pure-form-stacked">
        <input id='content_name' placeholder='name'/>
        <select id='selectOptions'>
        </select>
        <input type="file" id="file" name="file">
        <input type="submit" value="Submit">
</form>

This is my ajax, I got this adapted from answers here: How to send FormData objects with Ajax-requests in jQuery?

$("#contentAddForm").submit(function(e) {
       e.preventDefault(); 


      if($("#name").val() == ""){
        alert("No name picked");
        return;
      }


       var fd = new FormData();    
       fd.append('file', $( '#file' )[0].files[0]);
       fd.append('name', $("#content_name").val());
       fd.append('selectedOption', $('#selectOptions option:selected').val());

        $.ajax({
            type: 'POST',
            url: '/dbUserContentAdd',
            data: fd,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            success: function(data) {
                alert(data);
            },
            failure: function(data){
                alert(data);
            }
        });



    });

This is my python side, adapted from http://flask.pocoo.org/docs/0.10/patterns/fileuploads/

 #access via myURL.com/static/img/myImage.png
 UPLOAD_FOLDER = '/static/img'
 ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])

 @app.route('/dbUserContentAdd', methods=['GET', 'POST'])
 @login_required
 @confirm_email_required
 def upload_file():
     if request.method == 'POST':
         file = request.files['file']
         if file and allowed_file(file.filename):
             filename = secure_filename(file.filename)
             file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
             name = request.form.get('name', '')
             selectedOption = request.form.get('selectedOption', '')
                ...
             return "SUCCESS"

     return 'NOT_POST'
Community
  • 1
  • 1
applecrusher
  • 5,508
  • 5
  • 39
  • 89

1 Answers1

1
<script>      
document.getElementById('file').onchange = function () {
            var formdata = new FormData(); //FormData object
            var fileInput = document.getElementById('file');
            //Iterating through each files selected in fileInput
            for (i = 0; i < fileInput.files.length; i++) {
                //Appending each file to FormData object
                formdata.append(fileInput.files[i].name, fileInput.files[i]);
            }

            //Creating an XMLHttpRequest and sending
            var xhr = new XMLHttpRequest();
            var url = encodeURI('posturl');
            xhr.open('POST', url);
            xhr.send(formdata);
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    $('#returnMessage').html(xhr.responseText);
                }
            }
        }
</script>

try the above code to send file using Ajax.

AKASH
  • 416
  • 1
  • 7
  • 19