当图片可为PNG或JPEG时,如何指定http.MultipartFile的MediaType及Content-Type?
图片上传的MediaType与Content-Type设置说明
问题1:当媒体类型支持PNG、JPEG格式时,http.MultipartFile中需指定的MediaType
- JPEG格式:使用
MediaType('image', 'jpeg') - PNG格式:使用
MediaType('image', 'png')
问题2:JPEG/PNG格式图片对应的Content-Type媒体类型
- JPEG图片:
image/jpeg - PNG图片:
image/png
代码示例
以下是分别针对JPEG和PNG图片的上传代码示例:
JPEG图片上传
var postUri = Uri.parse('$serverUrl/store/signup'); var request = http.MultipartRequest('POST', postUri) ..fields['username'] = 'Username' ..files.add(await http.MultipartFile.fromPath( 'profilePic', profilePic!.path, contentType: MediaType('image', 'jpeg'), // 对应Content-Type: image/jpeg )); var response = await request.send();
PNG图片上传
var postUri = Uri.parse('$serverUrl/store/signup'); var request = http.MultipartRequest('POST', postUri) ..fields['username'] = 'Username' ..files.add(await http.MultipartFile.fromPath( 'profilePic', profilePic!.path, contentType: MediaType('image', 'png'), // 对应Content-Type: image/png )); var response = await request.send();
内容的提问来源于stack exchange,提问作者Flutter Dev
相关产品推荐
相关产品推荐

