簡體   English   中英

將圖像從android上傳到java servlet並保存

[英]Upload image from android to java servlet and save it

我一直在尋找這個,沒有什么對我有用。

我正在嘗試將圖像從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, 0, n);
        count += n;
    }
    return count;
}

你誤解了這個問題。 圖像文件不為空,但圖像文件已損壞,因為您將整個HTTP多部分請求主體存儲為圖像文件,而不是從HTTP多部分請求主體中提取包含該圖像的部分。

您需要HttpServletRequest#getPart()來獲取多部分請求主體的各個部分。 如果您已經使用Servlet 3.0(Tomcat 7,Glassfish 3等),請首先使用@MultipartConfig注釋您的servlet

@WebServlet("/GetPictureFromClient")
@MultipartConfig
public class GetPictureFromClient extends HttpServlet {
    // ...
}

然后按如下方式修復你的doPost() ,按名稱抓取零件,然后將它的主體作為輸入流:

InputStream in = request.getPart("userfile").getInputStream();
// ...

如果你還沒有使用Servlet 3.0,那么就抓住Apache Commons FileUpload 有關詳細示例,請參閱此答案: 如何使用JSP / Servlet將文件上載到服務器?

哦,請擺脫Netbeans生成的processRequest()方法。 doGet()doPost()委托給單個processRequest()方法絕對不是正確的方法,它只會混淆不使用Netbeans的其他開發人員和維護人員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM