
我正在尝试将图像从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();} 我在服务器端的代码:
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();} 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,n); count += n; } return count;}@H_502_22@解决方法 你误解了这个问题.图像文件不为空,但图像文件已损坏,因为您将整个http多部分请求主体存储为图像文件,而不是从http多部分请求主体中提取包含该图像的部分. 您需要HttpServletRequest#getPart()才能获取多部分请求正文的各个部分.如果您已经使用Servlet 3.0(Tomcat 7,Glassfish 3等),请先使用@MultipartConfig注释您的servlet
@WebServlet("/GetPictureFromClIEnt")@MultipartConfigpublic class GetPictureFromClIEnt extends httpServlet { // ...} 然后按如下方式修复你的doPost()以按名称抓取零件,然后将其身体作为输入流:
inputStream in = request.getPart("userfile").getinputStream();// ... 如果您还没有使用Servlet 3.0,请抓住Apache Commons FileUpload.有关详细示例,请参阅此答案:How to upload files to server using JSP/Servlet?
哦,请摆脱Netbeans生成的processRequest()方法.将doGet()和doPost()委托给单个processRequest()方法绝对不是正确的方法,它只会混淆不使用Netbeans的其他开发人员和维护人员.
@H_502_22@ @H_502_22@ 总结以上是内存溢出为你收集整理的将图像从android上传到java servlet并保存全部内容,希望文章能够帮你解决将图像从android上传到java servlet并保存所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)