我正在尝试将文件从 Android 上传到运行 Jersey 的 Tomcat 服务器。我将它打包在一个发布请求中。
这就是我在 Android 中所做的:
protected String doInBackground(String... params) {
String url = params[0];
String pathToFile = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost();
HttpResponse response = null;
httpPost.addHeader("Cookie", "sessionToken=~session");
try {
httpPost.setURI(new URI(url));
httpPost.setHeader("Accept", "application/json");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(pathToFile);
if(!file.exists())
return null;
FileBody fileBody = new FileBody(file);
entity.addPart("file", fileBody);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
return response.getStatusLine().toString();
在服务器中,我有以下内容:
我收到一个类型为“org.jvnet.mimepull.DataHead$ReadMultiStream”的 InputStream,在读取它时,读取到文件末尾后又回到 1024。
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON })
public Response uploadStorageFile(@Context UriInfo ui, @Context HttpHeaders hh, @FormDataParam("file")
InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail){
System.out.println(uploadedInputStream.getClass().getName());
String uploadedFileLocation = fileDetail.getFileName();
long size = fileDetail.getSize();
// save it
writeToFile(uploadedInputStream);
String output = "File uploaded to : ";
return Response.status(200).entity(output).build();
}
private void writeToFile(InputStream uploadedInputStream) {
try {
OutputStream out = new FileOutputStream(new File("test.jpg"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) > 0) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
如果文件长度为 8192,则循环如下:1024,2048,3072,4096,5120,6144,7168,8192,1024 -> 为什么?
注意:我已尝试使用 -1 的条件。
有人能弄清楚发生了什么吗?