private fun uploadFile(file: File) {
Thread {
val connection = URL(serverUrl).openConnection() as HttpURLConnection
connection.requestMethod = "PUT"
connection.doOutput = true
connection.setRequestProperty("Content-Type", "multipart/form-data")
val outputStream: OutputStream = BufferedOutputStream(connection.outputStream)
val fileInputStream = FileInputStream(file)
val buffer = ByteArray(4096)
var bytesRead: Int
while (fileInputStream.read(buffer).also { bytesRead = it } != -1) {
outputStream.write(buffer, 0, bytesRead)
}
outputStream.flush()
outputStream.close()
fileInputStream.close()
val responseCode = connection.responseCode
if (responseCode == HttpURLConnection.HTTP_OK) {
updateAvatar(file.name)
println("文件上传成功")
} else {
// 文件上传失败
println("文件上传失败")
}
}.start()
}
文件上传通过url,不需要获取token和密匙
最新推荐文章于 2024-03-07 21:36:23 发布