logo

该视频仅会员有权观看

立即开通课程「Flutter 移动端应用开发实践」权限。

¥
199
/ 年

准备上传文件用的请求

  • To upload a file, one must send a specific type of HTTP request using the 'http' package.
  • A 'multiple request' must be created to send the file upload request.
  • In the HTTP client API of the app service, a method must be defined that returns a 'Future<HttpClientResponse>'.
  • This new method requires two named parameters: 'file' (marked with 'require' and of type 'PlatformFile') to indicate the file to be uploaded, and 'postID' (required) to signify the ID of the content to which the file belongs.
  • Prepare the file upload API endpoint using a URI parsed with 'Uri.parse', using the 'apiBaseUrl' from the 'appConfig', appending 'files' and a 'post' query with the value of 'postID'.
  • Create a 'HttpRequest' named 'request' as a 'MultipartRequest', with the HTTP method set to 'POST' and URL set to the prepared URI.
  • The request headers need to include an 'Authorization' header with a token for user authentication.
  • Add the file to be uploaded to the request as a 'MultipartFile' by creating it with 'MultipartFile.fromPath', including the file's path, and setting its 'ContentType' (use 'MediaType' with 'image' as the first parameter and a file extension, or default to 'jpeg' if not provided).
  • Import the package 'http_parser.dart' to use 'MediaType'.
  • Add the prepared 'MultipartFile' to 'request.files'.
  • Return the result of executing 'request.send()'.