2012-03-18 7 views
6

android를 frontend로 and django를 backend로 업로드하려고합니다.Android-Django 이미지 업로드

는 모델 : 지금

def upload_photo(request): 
form=PhotoForm(request.POST,request.FILES) 
if request.method=='POST': 
    if form.is_valid(): 
     image = request.FILES['photo'] 
     title1 ='' 
     new_image = Photo(title=title1,photo=image,description='') 
     new_image.save() 
     response_data=[{"success": "1"}] 
     return HttpResponse(simplejson.dumps(response_data), mimetype='application/json') 

내가 노력하고 있어요 :

class Photo(models.Model): 
     title = models.CharField(max_length=255,blank=True) 
     photo = models.FileField(upload_to='photos') 
     description = models.TextField(blank=True) 
     uploaded = models.DateTimeField(auto_now_add=True) 
     modified = models.DateTimeField(auto_now=True) 

     class Meta: 
      db_table = 'media_photos' 

     def __unicode__(self): 
      return '%s' % self.title 

URL (R '^ 사진/업로드/$', 'upload_photo')를 URL로 여기 안드로이드에서 볼 수 있습니다.

 public void doFileUpload(String path){ 
     HttpURLConnection conn = null; 
     DataOutputStream dos = null; 
     DataInputStream inStream = null; 
     String lineEnd = "\r\n"; 
     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1*1024*1024; 
     String urlString = "http://"; // server ip 
     try 
     { 
     //------------------ CLIENT REQUEST 
     FileInputStream fileInputStream = new FileInputStream(new File(path)); 
     // open a URL connection to the Servlet 
     URL url = new URL(urlString); 
     // Open a HTTP connection to the URL 
     conn = (HttpURLConnection) url.openConnection(); 
     // Allow Inputs 
     conn.setDoInput(true); 
     // Allow Outputs 
     conn.setDoOutput(true); 
     // Don't use a cached copy. 
     conn.setUseCaches(false); 
     // Use a post method. 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Connection", "Keep-Alive"); 
     conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+" "); 
     dos = new DataOutputStream(conn.getOutputStream()); 
     dos.writeBytes(lineEnd); 
     dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + path + "\"" + lineEnd); 
     dos.writeBytes(lineEnd); 

     // create a buffer of maximum size 
     bytesAvailable = fileInputStream.available(); 
     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 necesssary after file data... 
     dos.writeBytes(lineEnd); 
     dos.writeBytes(lineEnd); 

     // close streams 
     Log.e("Debug","File is written"); 
     fileInputStream.close(); 
     dos.flush(); 
     dos.close(); 
     } 
     catch (MalformedURLException ex) 
     { 
      Log.e("Debug", "error: " + ex.getMessage(), ex); 
     } 
     catch (IOException ioe) 
     { 
      Log.e("Debug", "error: " + ioe.getMessage(), ioe); 
     } 

     //------------------ read the SERVER RESPONSE 
     try { 
       inStream = new DataInputStream (conn.getInputStream()); 
       String str; 
       while ((str = inStream.readLine()) != null) 
       { 
        Log.e("Debug","Server Response "+str); 
       } 
       inStream.close(); 
     } 
     catch (IOException ioex){ 
      Log.e("Debug", "error: " + ioex.getMessage(), ioex); 
     } 
     } 
} 

그러나 그것은 나에게 오류 제공 : 는 이제 이미지를 업로드 내 안드로이드 측 코드는

E/Debug(590): error: java.net.URISyntaxException: Authority expected at index 7: http:// 
+1

아마 urlString = "http : //" – zapl

+0

에 실제로 URL을 추가해야합니다. 이미 "private static String recordURL ="http://192.168.1.2/photos/upload/ ";" 이 업로드 기능을 호출합니다. 하지만 여전히 위에 주어진 오류를주고있다 – user1163236

+0

당신이 정의한 문자열을 사용합니까? 'URL url = 새 URL (recordURL); ' – zapl

답변

2

urlString = "http://192.168.1.2/photos/upload";

하지만 그것이 작동하지 않는 경우되어야한다 , 당신은 다른 오류를 얻을 것이다, 우리는 아마도 그 오류가 더 대답을해야합니다.

또한 실제 경계 문자열이 설정되지 않았으며 올바르게 사용하지 않는 것으로 보입니다.

http://stunningco.de/2010/04/25/uploading-files-to-http-server-using-post-android-sdk/ 그가 고유 한 경계 문자열을 사용하는 방법에 주목하고 출력 스트림에 씁니다.

질문에 답변을 표시해야합니다. 그렇게 할 때 응답을 얻는 것이 훨씬 더 성공적 일 것입니다.

0

이러한 어려움을 극복 한 후에도 장고 (Django)는 POST 매개 변수를 사용하여 csrfmiddlewaretoken을 제공해야합니다. 그리고 나는 당신이 안드로이드 장치에서 그것을 어떻게 얻을 수 있는지 보지 못합니다. Django 프론트 엔드 (즉, "템플릿") 이외의 것으로부터 Django 백엔드 코드 (즉, "뷰")를 호출하는 것을 방지하기위한 토큰이 설계되어 있습니다. 나는. 그것은 당신이하려고하는 것을 정확히하는 것을 방해하기 위해 고안되었습니다.

특정보기에서 csrf 기능을 비활성화 할 수 있습니다. "@csrf_exempt"데코레이터를 사용하십시오. 그리고 보안에 대해 충분히 신경 쓰는지 결정할 수 있고, csrf가 당신에게주는 것을 대체 할 수 있습니다.

또는 Android 앱에서 사진을 업로드하는 대신 사진을 업로드 할 웹 앱을 작성하고 Django 프로젝트가 해당 웹 앱을 제공하도록하십시오. 귀하의 안드로이드 애플 리케이션은 (의도로) 브라우저를 실행하고 그 웹 애플 리케이션을 가리킬 수 있습니다. 다음과 같은 코드가 있습니다 : https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html (아름다움 콘테스트에서 우승하지는 않지만 작동합니다.)