简体   繁体   English

从android客户端上传文件时为空Request.FILES

[英]Empty Request.FILES when uploading file from android client

i try upload file from android client to Django view but on uploading that request.FILES are always empty here is my django view code: views.py 我尝试将文件从android客户端上传到Django视图,但是在上传该request.FILES始终为空,这是我的django视图代码:views.py

def vw_reception_uploadimage(request, phonenumber):


    if request.method == 'POST':
            print request.META
            try:
                imagePath = '/home/user/Pictures/' + str(int(time.time() * 1000)) + '.jpg'
                destination = open(imagePath, 'wb+')
                for chunk in request.FILES["uploadedfile"].chunks():
                        destination.write(chunk)
                destination.close()
            except Exception as e:
                print e
                print request.FILES
            return HttpResponse("ok")

and here is my server file upload AsyncTask: class ServerFileUploadTask extends AsyncTask { 这是我的服务器文件上传AsyncTask:类ServerFileUploadTask扩展了AsyncTask {

    HttpURLConnection connection = null;  
    DataOutputStream outputStream = null;  
    DataInputStream inputStream = null;  

    String lineEnd = "\r\n";  
    String twoHyphens = "--";  
    String boundary = "----*****";  


    private Activity activity;
    private String filepath;
    ServerFileUploadTask(Activity activity,String filepath)
    {
        this.activity=activity;
        this.filepath=filepath;
    }


    @Override  
    protected Void doInBackground(String... uri) {  

        long length = 0;  
        int progress;  
        int bytesRead, bytesAvailable, bufferSize;  
        byte[] buffer;  
        int maxBufferSize = 2048 * 1024;// 256KB  

        try {  
            FileInputStream fileInputStream = new FileInputStream(new File(  
                    filepath));  
            File uploadFile = new File(this.filepath);  
            long totalSize = uploadFile.length(); // Get size of file, bytes  
            URL url = new URL(uri[0]);  
            connection = (HttpURLConnection) url.openConnection();  

            // Set size of every block for post  
            connection.setChunkedStreamingMode(2048 * 1024);// 256KB  

            // Allow Inputs & Outputs  
            connection.setDoInput(true);  
            connection.setDoOutput(true);  
            connection.setUseCaches(false);  

            // Enable POST method  
            connection.setRequestMethod("POST");  
            if(PrefSingleton.getInstance().readPreference("token", null)!=null){
                connection.setRequestProperty("AUTHORIZATION" , "Token "+PrefSingleton.getInstance().readPreference("token", null));
                }
            connection.setRequestProperty("Connection", "Keep-Alive");  
            connection.setRequestProperty("Charset", "UTF-8");  
            connection.setRequestProperty("Content-Type",  
                    "multipart/form-data; boundary=" + boundary);  

            outputStream = new DataOutputStream(  
                    connection.getOutputStream());  


            outputStream  
                    .writeBytes(twoHyphens + boundary + lineEnd+"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""  
                            + this.filepath + "\"" + lineEnd);  
            outputStream.writeBytes(lineEnd);  

            bytesAvailable = fileInputStream.available();  
            bufferSize = Math.min(bytesAvailable, maxBufferSize);  
            buffer = new byte[bufferSize];  

            // Read file  
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

            while (bytesRead > 0) {  
                outputStream.write(buffer, 0, bufferSize);  
                length += bufferSize;  
                progress = (int) ((length * 100) / totalSize);  
                publishProgress(progress);  

                bytesAvailable = fileInputStream.available();  
                bufferSize = Math.min(bytesAvailable, maxBufferSize);  
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);  
            }  
            outputStream.writeBytes(lineEnd);  
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens  
                    + lineEnd);  


            // Responses from the server (code and message)  
            int serverResponseCode = connection.getResponseCode();  
            String serverResponseMessage = connection.getResponseMessage();  

fileInputStream.close();  
            outputStream.flush();  
            outputStream.close();  

        } catch (Exception ex) {  


        }  
        return null;  
    }  



    @Override  
    protected void onPostExecute(Void result) {  

    }  

}  

i tried most examples with no success and most of them use methods and class that are deprecated 我尝试了大多数示例,但均未成功,并且大多数示例都使用了不推荐使用的方法和类

i using Django version 1.7 and development server on port 8080 我在端口8080上使用Django版本1.7和开发服务器

also using android version 4.2 there is some other examples that use httpentity and http entity builder that don't work for me 也使用android 4.2,还有其他一些使用httpentity和http实体生成器的示例对我不起作用

i can't find solution with above code but ended up solving problem by using Android Asynchronous Http Client library 我找不到上述代码的解决方案,但最终使用Android异步Http客户端库解决了问题

http://loopj.com/android-async-http/ http://loopj.com/android-async-http/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 客户端发送的请求在语法上不正确-上传文件时 - The request sent by the client was syntactically incorrect- when uploading a file Spring MVC:上传文件时“客户端发送的请求在语法上不正确”? - Spring MVC : “The request sent by the client was syntactically incorrect” when uploading a file? 通过Http POST请求从Android上传文件和其他数据 - Uploading files and other data from Android through Http POST request 无法通过 okhttp 填充 flask 中的 request.files - Unable to populate request.files in flask through okhttp IBM MobileFirst 7.1-从Android客户端发出请求时出错 - IBM MobileFirst 7.1 - Error when making request from Android Client 来自 Android 客户端的 HTTP 请求 - HTTP Request From Android Client 使用客户端证书和Android的HttpsURLConnection通过SSL上传文件 - Uploading a file over SSL with Client Side Certificate and Android's HttpsURLConnection 在Android中从Intent中选择文件时,文件返回空(“”) - File is returning empty (“”) when choosing from Intent in Android 从Android手机上传文件到FTP服务器? - Uploading a file to a FTP server from android phone? 文件未从android上传到php服务器 - file is not uploading from android to php server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM