Oha*_*dza 6 java android servlets image
我一直在寻找这个,没有什么对我有用.
我正在尝试将图像从Android应用程序上传到java servlet并将其保存在服务器中.我找到的每个解决方案都不适用于我.
我的代码目前做了什么:android应用程序将图像发送到servlet,当我试图保存它时,文件被创建,但它是空的:(
谢谢你的帮助!
我在android客户端的代码(i_file是设备上的文件位置):
public static void uploadPictureToServer(String i_file) throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://192.168.1.106:8084/Android_Server/GetPictureFromClient");
File file = new File(i_file);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Run Code Online (Sandbox Code Playgroud)
我在服务器端的代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
InputStream in = request.getInputStream();
OutputStream out = new FileOutputStream("C:\\myfile.jpg");
IOUtils.copy(in, out); //The function is below
out.flush();
out.close();
}
Run Code Online (Sandbox Code Playgroud)
IOUtils.copy代码:
public static long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
Run Code Online (Sandbox Code Playgroud)
你误解了这个问题.图像文件不为空,但图像文件已损坏,因为您将整个HTTP多部分请求主体存储为图像文件,而不是从HTTP多部分请求主体中提取包含该图像的部分.
您需要HttpServletRequest#getPart()获取多部分请求正文的部分.如果您已经使用Servlet 3.0(Tomcat 7,Glassfish 3等),请先使用.注释您的servlet@MultipartConfig
@WebServlet("/GetPictureFromClient")
@MultipartConfig
public class GetPictureFromClient extends HttpServlet {
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后doPost()按如下方式修复你的部分,按名称抓取部分,然后将其作为输入流:
InputStream in = request.getPart("userfile").getInputStream();
// ...
Run Code Online (Sandbox Code Playgroud)
如果你还没有使用Servlet 3.0,那么就抓住Apache Commons FileUpload.有关详细示例,请参阅此答案:如何使用JSP/Servlet将文件上载到服务器?
哦,请摆脱Netbeans生成的processRequest()方法.这绝对不是委托双方的正确方法doGet(),并doPost()以一个单一的processRequest()方法,它会只会混淆其他开发者和维护者谁不使用NetBeans.
| 归档时间: |
|
| 查看次数: |
9011 次 |
| 最近记录: |