我有一个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;
}
我得到的日志猫:
08-08 13:26:18.695: I/uploadFile(17202): HTTP Response is : INTERNAL SERVER ERROR: 500
08-08 13:26:18.695: E/Uploading Image(17202): Let see the response code: 500
08-08 13:26:18.695: I/Upload Result(17202): image upload un-successfuly
但我在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服务器。
答案 0 :(得分:0)
您在此处上传了uploaded_file
:
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
并期待myfile
:
myfile = request.FILES['myfile']
您的文件位于request.FILES['uploaded_file']
。