我的目标是创建一个类似whatsapp或电报的应用程序(仅限图片 - 无聊天) 我想将图片发送到我的Django服务器 这是我的模特:
class exchange(models.Model):
sender=models.CharField(verbose_name="sender",max_length=11)
reciever=models.CharField(verbose_name="reciever",max_length=11)
img=models.ImageField(verbose_name="imageAddress",upload_to="image/")
createTime=models.TimeField( auto_now_add=True,auto_now=False)
class users(models.Model):
number=models.CharField(verbose_name="userNumber",max_length=11)
name=models.CharField(verbose_name="name",max_length=40)
createTime=models.TimeField( auto_now_add=True,auto_now=False)
status=models.BooleanField(default=False)
class SMS(models.Model):
users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0)
code=models.PositiveSmallIntegerField(verbose_name="randomCode")
createTime=models.TimeField( auto_now_add=True,auto_now=False)
status=models.BooleanField(default=False)
交换班级==>存储发件人和收件人(电话号码)
img存储图像路径在Django服务器上.image存储在服务器上的目录中
用户类==>对于注册用户
短信类==>对于sms verificaion用户,如whatsup
我的序列化程序API:
class exchangeSerializer(ModelSerializer):
class Meta:
model=exchange
fields="__all__"
class SMSSerializer (ModelSerializer):
class Meta:
models=SMS
fields="__all__"
class usersSerializer(ModelSerializer):
class Meta:
model=users
fields="__all__"
我的观点API:
class exchangeShow(generics.ListAPIView):
queryset=exchange.objects.all()
serializer_class=exchangeSerializer
class SMSShow(generics.ListAPIView):
queryset=SMS.objects.all()
serializer_class=SMSSerializer
class usersShow(generics.ListAPIView):
queryset=users.objects.all()
serializer_class=usersSerializer
class exchangeDetailShow(generics.RetrieveAPIView):
queryset=exchange.objects.all()
serializer_class=exchangeSerializer
lookup_field='id'
class exchangeDelete(generics.DestroyAPIView):
queryset=exchange.objects.all()
serializer_class=exchangeSerializer
lookup_field='id'
class exchangeCreate(generics.CreateAPIView):
queryset=exchange.objects.all()
serializer_class=exchangeSerializer
class SMSCreate(generics.CreateAPIView):
queryset=SMS.objects.all();
serializer_class=SMSSerializer;
class usersCreate(generics.CreateAPIView):
queryset=users.objects.all()
serializer_class=usersSerializer
和网址API:
urlpatterns=[
path('exchange/',views.exchangeShow.as_view()),
path('sms/',views.SMSShow.as_view()),
path('users/',views.usersShow.as_view()),
path('exchange/<int:id>/delete',views.exchangeDelete.as_view()),
path('exchange/create',views.exchangeCreate.as_view()),
path('sms/create',views.SMSCreate.as_view()),
path('users/create',views.usersCreate.as_view()),
]
在凌空图书馆中 如何将图像从Android设备发送到Django并将其保存在服务器的目录中并将其存储在交换表(img)中并在接收器中的应用程序中显示
答案 0 :(得分:0)
我使用HttpURLConnection而不是Volley
public class AsyncUpload extends AsyncTask<Void,Void,String> {
private String charset,url,path,num,nam;
private boolean type;
public AsyncUpload(String url, String path,boolean type,String num,String nam){
this.path= path;
this.url = url;
this.charset="UTF-8";
this.type=type;
this.num=num;
this.nam=nam;
}
@Override
protected String doInBackground(Void... voids) {
Sender multipart = null;
String response;
try {
multipart = new Sender(url, path, charset);
if (type)
multipart.addFilePart();
multipart.addFormField("number", num);
multipart.addFormField("name", nam);
response=multipart.finish();
return response;
} catch (Exception e) {
Log.e("ERROR in AsyncUpload",e.toString() );
return "{\"success\":[]}";
}
}}
public class connector {
public static HttpURLConnection connect(String surl,String b) {
try {
URL url=new URL(surl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Cache-Control", "no-cache");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+b);
con.setRequestProperty("User-Agent", "CodeJava Agent");
return con;
}catch (MalformedURLException e){
} catch (IOException e) {
e.printStackTrace();
}
return null;
}}
public class Sender {
private String url, path;
private String boundary = null;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public Sender( String url, String path, String charset) throws IOException {
this.url = url;
this.path = path;
this.charset = charset;
boundary = "===" + System.currentTimeMillis() + "===";
httpConn = connector.connect(url, boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart()
throws IOException {
File uploadFile=new File(path);
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"photo\"; filename=\"" + fileName + "\"").append(LINE_FEED);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, bytesRead);
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED);
writer.flush();
}
public String finish() throws IOException {
StringBuilder response = new StringBuilder();
writer.flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.flush();
writer.close();
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
httpConn.disconnect();
outputStream.flush();
outputStream.close();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response.toString();
}}