当我上传包含我想在同一方法中使用的多个其他字段的文件时,我收到内部服务器错误500。但是,我似乎无法弄清楚到底出了什么问题。我在Python中使用Flask Upload,我不确定我是否遗漏了一些明显的东西。下面是我正在使用的HTML,Javascript和Python。任何帮助将不胜感激。
<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>
这是我的ajax,我在这里改编了答案: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);
}
});
});
这是我的python方面,改编自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'
答案 0 :(得分: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>
尝试上面的代码使用Ajax发送文件。