Android Java文件上传到Django后端

问题描述 投票:0回答:1

我已经无情地尝试从我的JAVA / Android项目创建成功的文件上传到Django / Python后端。

我要上传的文件是一个存储在手机上的wav音频文件。

我想混合两组代码。

我正在使用的Android代码取自:How to upload a WAV file using URLConnection

public class curlAudioToWatson extends AsyncTask<String, Void, String> {
        String asrJsonString="";
        @Override
        protected String doInBackground(String... params) {
            String result = "";
            try {
                Log.d("Msg","**** UPLOADING .WAV to ASR...");
                URL obj = new URL(ASR_URL);
                HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
                //conn.setRequestProperty("X-Arg", "AccessKey=3fvfg985-2830-07ce-e998-4e74df");
                conn.setRequestProperty("Content-Type", "audio/wav");
                conn.setRequestProperty("enctype", "multipart/form-data");
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                String wavpath=mRcordFilePath;
                File wavfile = new File(wavpath);
                boolean success = true;
                if (wavfile.exists()) {
                    Log.d("Msg","**** audio.wav DETECTED: "+wavfile);
                }
                else{
                    Log.d("Msg","**** audio.wav MISSING: " +wavfile);
                }

                String charset="UTF-8";
                String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
                String CRLF = "\r\n"; // Line separator required by multipart/form-data.

                OutputStream output=null;
                PrintWriter writer=null;
                try {
                    output = conn.getOutputStream();
                    writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
                    byte [] music=new byte[(int) wavfile.length()];//size & length of the file
                    InputStream             is  = new FileInputStream       (wavfile);
                    BufferedInputStream bis = new BufferedInputStream   (is, 16000);
                    DataInputStream dis = new DataInputStream       (bis);      //  Create a DataInputStream to read the audio data from the saved file
                    int i = 0;
                    copyStream(dis,output);
                }
                catch(Exception e){

                }

                conn.connect();

                int responseCode = conn.getResponseCode();
                Log.d("Msg","POST Response Code : " + responseCode + " , MSG: " + conn.getResponseMessage());

                if (responseCode == HttpURLConnection.HTTP_OK) { //success
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    Log.d("Msg","***ASR RESULT: " + response.toString());


                    JSONArray jresponse=new JSONObject(response.toString()).getJSONObject("Recognition").getJSONArray("NBest");
                    asrJsonString=jresponse.toString();

                    for(int i = 0 ; i < jresponse.length(); i++){
                        JSONObject jsoni=jresponse.getJSONObject(i);
                        if(jsoni.has("ResultText")){
                            String asrResult=jsoni.getString("ResultText");
                            //ActionManager.getInstance().addDebugMessage("ASR Result: "+asrResult);
                            Log.d("Msg","*** Result Text: "+asrResult);
                            result = asrResult;
                        }
                    }
                    Log.d("Msg","***ASR RESULT: " + jresponse.toString());

                } else {
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    Log.d("Msg","POST FAILED: " + response.toString());
                    result = "";
                }
            } catch (Exception e) {
                Log.d("Msg","HTTP Exception: " + e.getLocalizedMessage());
            }
            return result; //"Failed to fetch data!";
        }

        @Override
        protected void onPostExecute(String result) {
            if(!result.equals("")){
                Log.d("Msg","onPostEXECUTE SUCCESS, consuming result");

                //sendTextInputFromUser(result);
                //ActionManager.getInstance().addDebugMessage("***ASR RESULT: "+asrJsonString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }else{
                Log.d("Msg","onPostEXECUTE FAILED" );
            }
        }
    }


    public void copyStream( InputStream is, OutputStream os) {
        final int buffer_size = 4096;
        try {

            byte[] bytes = new byte[buffer_size];
            int k=-1;
            double prog=0;
            while ((k = is.read(bytes, 0, bytes.length)) > -1) {
                if(k != -1) {
                    os.write(bytes, 0, k);
                    prog=prog+k;
                    double progress = ((long) prog)/1000;///size;
                    Log.d("Msg","UPLOADING: "+progress+" kB");
                }
            }
            os.flush();
            is.close();
            os.close();
        } catch (Exception ex) {
            Log.d("Msg","File to Network Stream Copy error "+ex);
        }
    }

Django后端代码取自:https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html,我正在使用简单的上传:

def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        myfile = request.FILES['myfile']
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)
        return render(request, 'core/simple_upload.html', {
            'uploaded_file_url': uploaded_file_url
        })
    return render(request, 'core/simple_upload.html')

我已经使用@csrf_exempt禁用了CSRF。

我收到错误“MultiValueDictKeyError”,因为Java没有发布名为'myfile'的文件,要求抓住request.FILES ['myfile']。是否尝试删除['myfile']并使用request.FILES,但后来我收到错误

filename = fs.save(myfile.name, myfile)

说没有名字可以取。

我可以发布文件以便它被捕获

request.FILES['myfile']

或者是否有更好/更简单的Django后端代码用于与Android / IOS进行通信。

提前谢谢,如果这是一个愚蠢的问题我很抱歉,但我已经死了。

android python django file-upload httpurlconnection
1个回答
0
投票

在这里,我再次回答我自己的问题。

我从Android:How to upload .mp3 file to http server?找到了以下代码

使用它而不是How to upload a WAV file using URLConnection并改变线:dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"myfile\";filename=\"" + existingFileName + "\"" + lineEnd);

解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.