我遇到了一些问题,之前我已经解决了。非常感谢所有回答问题的人。
我正在尝试将图像从我的 android 应用程序上传到服务器(Servelet)。我还模拟了包含一个 jpeg 图像的 SD 卡。
我已经能够与服务器建立连接并收到一些消息。但到目前为止,我还无法在服务器上检索图像。我在服务器上收到错误消息。我正在使用多部分选项。代码如下。请看看,让我知道我做错了什么。
安卓端
String path="http://10.0.2.2:8080/ImageLocalizer/Localize";
String pathToFile="/sdcard/building.jpg";
text1.setText(path);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToFile) );
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("FileName", "building.jpg");
DataOutputStream outputStream =new DataOutputStream( connection.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
fileInputStream.close();
outputStream.flush();
outputStream.close();
text1.setText(path);
BufferedReader in =new BufferedReader(new InputStreamReader( connection.getInputStream() ) );
String response="",msg="";
while ( (response = in.readLine()) != null ) {
msg+=response;
}
text2.setText(msg);
}
catch (Exception ex)
{}
}
服务端
doPost()
{
System.out.println("RUNNING");
InputStream in = request.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuffer buf = new StringBuffer();
String line;
PrintWriter out = response.getWriter();
out.println("Image copied !!");
out.close();
try
{
PrintWriter out1=response.getWriter();
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String s[]=new String[30];
byte i=0;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart)
{
List items=upload.parseRequest(request);
Iterator iterator=items.iterator();
while(iterator.hasNext())
{
FileItem fitem=(FileItem)iterator.next();
if(!fitem.isFormField())
{
StringBuffer s2=new StringBuffer(fitem.getName());
if(s2!=null && s2.length()>0)
{
File fl=new File("H:\\abcd.jpg");
fitem.write(fl);
}
}
if(fitem.isFormField())
{
s[i]=fitem.getString();
i++;
}
}
}
}catch(Exception e){e.printStackTrace();}
}