Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix file upload through htmx.ajax #2778

Merged
merged 2 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -3918,7 +3918,7 @@ var htmx = (function() {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key].forEach === 'function') {
obj[key].forEach(function(v) { formData.append(key, v) })
} else if (typeof obj[key] === 'object') {
} else if (typeof obj[key] === 'object' && !(obj[key] instanceof Blob)) {
formData.append(key, JSON.stringify(obj[key]))
} else {
formData.append(key, obj[key])
Expand Down
52 changes: 52 additions & 0 deletions test/core/parameters.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,4 +312,56 @@ describe('Core htmx Parameter Handling', function() {
this.server.respond()
form.innerHTML.should.equal('Clicked!')
})

it('file is correctly uploaded with file input', function() {
this.server.respondWith('POST', '/test', function(xhr) {
should.equal(xhr.requestHeaders['Content-Type'], undefined)

const file = xhr.requestBody.get('file')
file.should.instanceOf(File)
file.name.should.equal('test.txt')

xhr.respond(200, {}, 'OK')
})

const form = make('<form hx-post="/test" hx-target="#result" hx-encoding="multipart/form-data">' +
'<input type="file" name="file">' +
'<button type="submit"></button>' +
'</form>')
const input = form.querySelector('input')
const file = new File(['Test'], 'test.txt', { type: 'text/plain' })
const dataTransfer = new DataTransfer()
dataTransfer.items.add(file)
input.files = dataTransfer.files

const result = make('<div id="result"></div>')

form.querySelector('button').click()
this.server.respond()
result.innerHTML.should.equal('OK')
})

it('file is correctly uploaded with htmx.ajax', function() {
this.server.respondWith('POST', '/test', function(xhr) {
should.equal(xhr.requestHeaders['Content-Type'], undefined)

const file = xhr.requestBody.get('file')
file.should.instanceOf(File)
file.name.should.equal('test.txt')

xhr.respond(200, {}, 'OK')
})

const div = make('<div hx-encoding="multipart/form-data"></div>')

htmx.ajax('POST', '/test', {
source: div,
values: {
file: new File(['Test'], 'test.txt', { type: 'text/plain' })
}
})

this.server.respond()
div.innerHTML.should.equal('OK')
})
})