如何在servlet中保存multipart / form-data中的数据并将此数据保存到db?

时间:2015-11-18 06:47:50

标签: android servlets

public void saveData(HttpServletRequest request,HttpServletResponse response) throws IOException {
    try {
        boolean checkMultiPart = ServletFileUpload.isMultipartContent(request);
        System.out.println(checkMultiPart);
        //fin = request.getInputStream();
        Part part = request.getPart("pic");
        fin = part.getInputStream();
        System.out.println(fin);
        writer = response.getWriter();
        if(fin != null){
            fin.read();
            System.out.println("Inside Function");
            query = "INSERT INTO SAVEPIC(picID,PIC) VALUES (picIncVal.nextval,?)";
            Class.forName(DB_DRIVER);
            connection = DriverManager.getConnection(DB_URL, DB_USER,DB_PASSWORD);
            connection.setAutoCommit(false);
            insertStatement = connection.prepareStatement(query);
            insertStatement.setBinaryStream(1, fin, fin.available());
            row = insertStatement.executeUpdate();
            connection.commit();
            System.out.println("Save To Data Base");
        }
        if (row > 0)
            writer.print("SUCCESS");
        else
            writer.print("FAILED");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        writer.print("Pic Value is Null");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if(fin != null)
                fin.close();
            if(writer != null)
                writer.close();
            if (connection != null) {
                insertStatement.close();
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}

我想在multipart / form-data中存储我从android发送的图像。任何人都可以给我建议我该怎么做。

通过此代码,只有一些位存储在db中,而不是整个映像。

提前致谢。

0 个答案:

没有答案