我想将图像从画廊/相机发送到服务器。该图像被压缩Bitmap
,并被转换为ByteArray
。问题是服务器返回错误-> file is not JPEG
。这意味着服务器无法将我的内容识别为JPEG。有什么事吗
这是我对多部分请求的API调用。
val data: ByteArray = convertBitmapToByteArray(bmp)
val con = url.openConnection() as HttpURLConnection
con.apply {
requestMethod = method
useCaches = false
doOutput = true
doInput = true
addRequestProperty("Connection", "Keep-Alive")
addRequestProperty("Cache-Control", "no-cache")
addRequestProperty("Content-Type", "multipart/form-data")
addRequestProperty("X-API-Key", apiType.apiKey)
addRequestProperty("X-Session", session)
}
val request = DataOutputStream(con.outputStream)
request.apply {
writeBytes("$TWO_HYPHENS$BOUNDARY$CRLF")
writeBytes("Content-Disposition: form-data; name=\"" +
ATTACHMENT_NAME + "\";filename=\"" +
filename + "\"" + CRLF)
writeBytes(CRLF)
write(data)
writeBytes(CRLF)
writeBytes("$TWO_HYPHENS$BOUNDARY$TWO_HYPHENS$CRLF")
flush()
close()
}
val code = con.responseCode
if (code/100 != 2) {
if (code == 502){
//handle special error
} else if (code >= 400) {
//handle errors
}
//handle errors
}
return getHttpResponseAsJson(con)
转换位图:
fun convertBitmapToByteArray(bmp: Bitmap): ByteArray{
val stream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream)
return stream.toByteArray()
}