如何使用 JSP 客户端通过 JAX-WS 将图像上传到 mysql 数据库?

How to upload an image to a mysql database with JAX-WS using a JSP client?

我正在尝试使用 GlassFish 服务器中 Java 开发的 SOAP Web 服务将图像上传到 mysql 数据库。 JSP 中的客户端正在使用此 Web 服务。我搜索了很多,但找不到合适的答案。

有人能帮帮我吗?提前致谢!

您必须使用 JAX-WS 或其他框架(如 CXF、Axis 或 Spring WS.The 创建客户端代码来使用 Web 服务,客户端代码将位于您的应用程序的控制器中。 JSP 将作为视图将要发送到服务的数据发送到控制器,然后控制器将与 web 服务进行交互。

这是 JSP 和控制器的框架:

<form action="${request.contextPath}/path/to/controller" method="POST" enctype="multipart/form-data">
    File to upload:
    <input type="file" name="fileData" />
    <br />
    <!-- probably more fields, depending on your requirements... -->
    <input type="submit" value="Upload file">
</form>

控制器代码(因为您没有指定要使用的特定框架,所以我使用的是普通 Servlet):

@WebServlet("/path/to/controller")
public class FileUploadToWSServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        //consume the data from JSP

        //pass the data received from JSP
        //to send it to consume the JAX-WS service
    }
}

通过 scriptlet 可以尝试直接从 JSP 使用 Web 服务,但应避免使用它,因此不推荐使用这种方法,这不是我的答案的一部分。

这是我的问题的完整答案。我不相信您会遇到 .jsp 页面的问题,您只需要根据需要创建一个包含输入的表单。处理上传的代码如下:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = "";
    String comment = "";

    if(ServletFileUpload.isMultipartContent(request)){
        try {

            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for(FileItem item : multiparts){
                if(!item.isFormField()){
                    name = new File(item.getName()).getName();
                    item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                } else {
                    if ("comment".equals(item.getFieldName())) {
                         comment = item.getString();
                     // Whatever you have to do with the comment
                    }
                }
            }
           addPhoto((int) request.getSession().getAttribute("id"), UPLOAD_DIRECTORY + File.separator + name , comment);
           request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
        }          
    }else{
        request.setAttribute("message","Sorry this Servlet only handles file upload request");
    }
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}