如何将 Android SD 卡中的图像上传到 Django 服务器?

How do you upload an image from Android SD card to Django server?

我有 URI 地址,主要是想在 html 页面上显示图像。 html 页面只显示一个空图像。我真的不知道该怎么做,因为我是 Android 和 Django 的初学者。这是我的代码:

Android 工作室代码。我在示例 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')

models.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>
 <title>Image Upload</title>
 <style>

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

谢谢!

如果我非常理解你的问题,这应该适用于 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 upload to django server'