skip to Main Content

I am able to upload images via API to WordPress but not audio files, it gives HTTP 500 error when I try to pass the Audio file to the method. But when I pass the image it uploads successfully,
here is the function.

I’m using the Dio package.


Future<bool> UploadFileToWordpress(File file) async {

    try {
      final token = MyConstant.token;

      String apiURL = "https://prostate-wrench.000webhostapp.com";
      String uri = "$apiURL/wp-json/wp/v2/media";

      String fileName = file.path
          .split('/')
          .last;
      print(fileName);

      FormData data = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          file.path,
          filename: fileName,
        ),
      });

      Dio dio = Dio(BaseOptions(
          headers: {
            'Authorization': 'Bearer ${MyConstant.token}'
          },
          contentType: "application/json")
      );
      var response = await dio.post(uri, data: data);
      print(response.statusMessage);
      if (response.statusCode == 201) {
        return true;
      } else {
        return false;
      }

   
    }catch(e){
      print(e.toString());
      return false;
    }
  }

2

Answers


  1. Chosen as BEST ANSWER

    Got it.. added ".mp3" extension with filename variable and its perfect now


  2. FormData data = FormData.fromMap({
            "file": await MultipartFile.fromFile(
              file.path,
              filename: fileName,
              contentType: ...,//need to add this part 
            ),
          });
    

    import ‘package:mime/mime.dart’; //don’t forget import

    var lookUpMime =lookupMimeType(file.path);
    

    now need to split type

          var mimeString = mimeType.split('/')[0];
          var mimeType = mimeType.split('/')[1];
    

    and add it as contentType:

    contentType: MediaType(mimeString, mimeType),
    

    I think it helps

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search