I'm trying to upload a binary file from iOS to a server on local Wifi. The uploader on the server works fine from its web page, but I can't get it to upload from Swift. It looks to me like my request is not properly formed, but I haven't been able to figure out what it's missing.
Thanks for any help.
~ Nancy
Here's my upload routine:
func uploadFile() {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let updateURL = URL(string: ("http://" + currentBaseString + "/update"))
var request = URLRequest(url: updateURL!)
print("SETUP Upload Request: ", request)
request.httpMethod = "POST"
guard let fileURL = Bundle.main.url(forResource: "R2-0701", withExtension: "bin") else {
print("Failed to create URL for file.")
return
}
do {
let data = try Data(contentsOf: fileURL)
print("SETUP Found the data file\n")
request.httpBody = data
let task = URLSession.shared.uploadTask(with: request as URLRequest, fromFile: fileURL) { data, response, error in
if error != nil {
print ("RRC Task error: \(String(describing: error))")
return
}
guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode) else {
print ("Server error")
return
}
if let mimeType = response.mimeType,
mimeType == "multipart/form-data",
let updateData = data,
let dataString = String(data: updateData, encoding: .utf8) {
print ("got data: \(dataString)")
}
}
task.resume()
}
catch {
print("Error opening file: \(error)")
}
}
My URL construction is fine, it works for GET requests. "R2-0701.bin" is the filename of a file added to the project.
Here's the server HTML:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'>
</script>
<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>
<table cellpadding = '10' align='center''>
<tr>
<td bgcolor='AA0000' align='center' style='color:white;'>
<p font-color='white' text-size='12' >
<b>Reprogram</b>
</p>
</td>
</tr>
<tr>
<td>
<input type='file' name='update'>
</td>
</tr>
<tr>
<td align='center'>
<input type='submit' value='Update'>
</form>
</td>
</tr>
<tr>
<td align='center'>
<div id='prg'>progress: 0%</div>
</td>
</tr>
</table>
<script>
$('form').submit(function(e){
e.preventDefault();
var form = $('#upload_form')[0];
var data = new FormData(form);
$.ajax({
url: '/update',
type: 'POST',
data: data,
contentType: false,
processData:false,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
var per = evt.loaded / evt.total;
$('#prg').html('progress: ' + Math.round(per*100) + '%');
}
}, false);
return xhr;
},
success:function(d, s) {
console.log('success!')
},
error: function (a, b, c) {
}
});
});
</script>;
Here's the output:
SETUP Upload Request: http://192.168.86.41/update
SETUP Found the data file
2022-07-04 17:21:52.075958-0600 RoadrunnerComfort[5034:11127394] Task <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7> HTTP load failed, 1048855/0 bytes (error code: -1005 [4:-4])
2022-07-04 17:21:52.082677-0600 RoadrunnerComfort[5034:11127423] Task <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283fb49c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x2812ecc80 [0x22eb841b8]>{length = 16, capacity = 16, bytes = 0x10020050c0a856290000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.86.41/update, NSErrorFailingURLKey=http://192.168.86.41/update, _kCFStreamErrorDomainKey=4}
2022-07-04 17:21:52.083212-0600 RoadrunnerComfort[5034:11127396] [tcp] tcp_input [C7:2] flags=[R.] seq=3409008496, ack=2962928595, win=5744 state=LAST_ACK rcv_nxt=3409008496, snd_una=2962927159
RRC Task error: Optional(Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x283fb49c0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x2812ecc80 [0x22eb841b8]>{length = 16, capacity = 16, bytes = 0x10020050c0a856290000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalUploadTask <25F2EC07-30D7-4532-BD6A-D35A41716AF2>.<7>"
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=http://192.168.86.41/update, NSErrorFailingURLKey=http://192.168.86.41/update, _kCFStreamErrorDomainKey=4})`