2015-12-07 82 views
0

我有URI地址,基本上是試圖在html頁面上顯示圖像。該html頁面只顯示一個空的圖像。我真的不知道該怎麼做,因爲我是Android和Django的初學者。這裏是我的代碼:如何從Android SD卡上傳圖片到Django服務器?

Android Studio代碼。我在做我的樣本Java文件包的新文件:

public class ImageHTTPPostRequest 
{ 
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://127.0.0.1:8000/"; // server ip 
    try 
    { 
     //------------------ CLIENT REQUEST 
     FileInputStream fileInputStream = new FileInputStream(new File(CameraIntentActivity.photoUriPath)); 
     // open a URL connection to the Servlet 
     URL url = new URL("http://127.0.0.1:8000/"); 
     // 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); 
    } 
} 
} 

這裏是我的Django代碼:

views.py

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

forms.py

class PhotoForm(forms.Form): 
    uploadImage = forms.FileField(label='uploadImage') 

模型.py

class Photo(models.Model): 
user = models.CharField(max_length=5000) 
photo = models.FileField(upload_to='memorylane/static/images') 
uploaded = models.DateTimeField(auto_now_add=True) 
modified = models.DateTimeField(auto_now=True) 

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

然後是html頁面。我真的不知道有什麼在這裏:

<!DOCTYPE html> 
 
<html lang="en"> 
 

 
{% load staticfiles %} 
 
{% include 'head.html' %} 
 
<head> 
 
\t <title>Image Upload</title> 
 
\t <style> 
 

 
\t </style> 
 
</head> 
 
<body> 
 
\t <img class="uploadImage" src="placeholder" width="500" height="500"> 
 
</body> 
 
</html>

謝謝!

+0

請註明你所面對的問題,即任何異常發生或代碼不工作? – VVJ

+0

當我運行html頁面imageUpload時,它說:視圖沒有返回一個HttpResponse對象。它返回None而不是。 – aquaelmo

+0

設置內容類型不是MIME類型 – VVJ

回答

0

如果我很好地理解你的問題,這應該適用於html頁面渲染。

views.py

def imageUpload(request): 
    form = PhotoForm() 
    if request.method=='POST': 
     form = PhotoForm(request.POST, request.FILES) 
     if form.is_valid(): 
      image = request.FILES['photo'] 
      new_image = Photo(photo=image) 
      new_image.save() 
      response_data=[{"success": "1"}] 
      return HttpResponse(simplejson.dumps(response_data), mimetype='application/json') 
    return render(request, 'page.html',{"form": form}, context_instance=RequestContext(request)) 

,但我必須承認,我不明白你的意思「的Android上傳到服務器的Django」

相關問題