Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
django视图中的图像处理函数未保存android客户端上载的PNG图像_Android_Python_Django_Curl_Image Uploading - Fatal编程技术网

django视图中的图像处理函数未保存android客户端上载的PNG图像

django视图中的图像处理函数未保存android客户端上载的PNG图像,android,python,django,curl,image-uploading,Android,Python,Django,Curl,Image Uploading,我有一个django视图函数,是我为处理使用http post上传的图像而编写的 方法:view.py @csrf_exempt def upload_image(request): print "image file" if request.method == 'POST': print "posted" myfile = request.FILES['myfile'] filename = myfile.name

我有一个django视图函数,是我为处理使用http post上传的图像而编写的

方法:view.py

@csrf_exempt
def upload_image(request):
     print "image file"
     if request.method == 'POST':
        print "posted"
        myfile = request.FILES['myfile']
        filename = myfile.name
        print filename
        fd = open('/home/ubuntu/server/smartDNA/media/documents/' + filename,     'wb+',00777)
        print "open file object"
        imagefile='/media/documents/'+filename
        imdoc=ImageDocuments(docfile=imagefile)
        imdoc.save()
        for chunk in myfile.chunks():
                 fd.write(chunk)
        fd.close()
        return HttpResponse("OK")
     else:
        return HttpResponse("Not Ok")
然后我在这里写了一段android代码:

private class UploadImageTast extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) { 
        int response= uploadFile(params[0]+"/pradeep.png");
        Log.e("Uploading Image", "Let see the response code: "+response);
        return Integer.toString(response);
    }
    @Override
    protected void onPostExecute(String result) {
        if(result=="200"){
        Log.i("Upload Result", "image uploaded successfuly");
        }else{
        Log.i("Upload Result", "image upload un-successfuly");
        }
    }
}
public int uploadFile(String sourceFileUri) {
      String upLoadServerUri = "http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/upload_image/";
      String fileName = sourceFileUri;

      HttpURLConnection conn = null;
      DataOutputStream dos = null; 
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesRead, bytesAvailable, bufferSize;
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024;
      File sourceFile = new File(sourceFileUri);
      if (!sourceFile.isFile()) {
       Log.e("uploadFile", "Source File Does not exist");
       return 0;
      }
          try { // open a URL connection to the view
           FileInputStream fileInputStream = new FileInputStream(sourceFile);
           URL url = new URL(upLoadServerUri);
           conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
           conn.setDoInput(true); // Allow Inputs
           conn.setDoOutput(true); // Allow Outputs
           conn.setUseCaches(false); // Don't use a Cached Copy
           conn.setRequestMethod("POST");
           conn.setRequestProperty("Connection", "Keep-Alive");
           conn.setRequestProperty("ENCTYPE", "multipart/form-data");
           conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
           conn.setRequestProperty("uploaded_file", fileName);
           dos = new DataOutputStream(conn.getOutputStream());    
           dos.writeBytes(twoHyphens + boundary + lineEnd);
           dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
           dos.writeBytes(lineEnd);     
           bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size     
           bufferSize = Math.min(bytesAvailable, maxBufferSize);
           buffer = new byte[bufferSize];     
           // read file and write it into form...
           bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

           while (bytesRead > 0) {
             dos.write(buffer, 0, bufferSize);
             bytesAvailable = fileInputStream.available();
             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             bytesRead = fileInputStream.read(buffer, 0, bufferSize);              
            }

           // send multipart form data necessary after file data...
           dos.writeBytes(lineEnd);
           dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

           // Responses from the server (code and message)
           serverResponseCode = conn.getResponseCode();
           String serverResponseMessage = conn.getResponseMessage();                
           Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
           if(serverResponseCode == 200){
               Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + "success");               
           }   

           //close the streams //
           fileInputStream.close();
           dos.flush();
           dos.close();

      } catch (MalformedURLException ex) { 
          ex.printStackTrace();
          Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
      } catch (Exception e) {
          e.printStackTrace();             
          Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
      }
      return serverResponseCode; 
     }
但我在log cat上获得了状态500。我的处理程序似乎无法处理http post中的多部分上载。但是,当我使用curl命令以相同的方法上传图像时,它会工作,并且我能够上传图像。我成功使用并上载图像的CURL命令:

curl "http://ec2-72-44-51-113.compute-1.amazonaws.com:8001/upload_image/" -F myfile=@"/home/pradeep/Desktop/Deeksha.PNG"

在我看来,django的功能是否需要任何修改,或者是否需要任何其他方式。这样我就可以将png图像文件上传到django服务器。

您正在上传一个
上传的\u文件
这里:

dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
这里需要一个
myfile

myfile = request.FILES['myfile']
您的文件位于
request.FILES['uploaded\u file']

myfile = request.FILES['myfile']