Flutter/Dart - How to use Return Data from Http Post in a Conditional to avoid Duplicate upload?

旧街凉风 提交于 2020-08-10 19:15:50

问题


Upon clicking a FlatButton an audio file is uploaded to a directory on my server, renamed and the new path/name is saved to a PHP/mySQL database. I'd like to prevent the button from uploading the same file twice. But I can't use a mySQL query in a conditional as the name of the file has been changed before insertion into the database. So I've got the oldname of the file extracted from the response.body upon a successful 200 upload, but not sure how to get the oldname back to the button.

Here's the code for the FlatButton:

child: FlatButton(
        
                onPressed: () {
                
                    uploadAudio(
                        currentuserid: socialProvider.currentuserid,
                        filepath: _current.path);
                },          
              ),

And here's the uploadAudio method which returns a response from the MySQL query;

String oldname;

Future<String> uploadAudio({String currentuserid, String filepath}) async {

  final serverurl = "http://example.com/audiopostsfile.php";    
  var request = http.MultipartRequest('POST', Uri.parse(serverurl));
  request.fields['userid'] = currentuserid;    

  var multiPartFile = await http.MultipartFile.fromPath("audio", filepath,
      contentType: MediaType("audio", "mp4"));
        request.files.add(multiPartFile);
        request.send().then((result) async {
          http.Response.fromStream(result).then((response) {
                if (response.statusCode == 200) {
                  String serverResponse = response.body;
                  const start = "gxz";
                  const end = "zxg";
                  final startIndex = serverResponse.indexOf(start);
                  final endIndex = serverResponse.indexOf(end, startIndex + start.length);
                  oldname = serverResponse.substring(startIndex + start.length, endIndex);
                }
          });
   });
    return oldname;
  }

Any ideas how I can do this and prevent a duplicate upload?


回答1:


How about once the file is successfully uploaded to the server, you compute the checksum of the file and return that back. Before determining to enable the button and send the file to server, you can check to see if the checksum of the file you want to upload is different than the one that the server response. You can cache a list of these checksum to check against. If not then you can assume that the user want to override the old upload.



来源:https://stackoverflow.com/questions/63191309/flutter-dart-how-to-use-return-data-from-http-post-in-a-conditional-to-avoid-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!