简体   繁体   English

如何在servlet中处理上传的图像?

[英]How to process uploaded image in servlet ?

In jsp page I have uploaded a image file and I forwarded that Jsp page to a Servlet and I want to retrieve that image in Servlet and add that image to Database ....... Can anyone explain how to retrieve image in servlet and add that image to database?在 jsp 页面中,我上传了一个图像文件,并将该 Jsp 页面转发到了一个 Servlet,我想在 Servlet 中检索该图像并将该图像添加到数据库中......任何人都可以解释如何在 servlet 中检索图像和将该图像添加到数据库? Eg : We can retrieve string using request.getParameter("string");例如:我们可以使用 request.getParameter("string"); 检索字符串。 In the same way is there any pre-defined method to retrive image?同样,是否有任何预定义的方法来检索图像? Eg: prepareStatement.setInt(colomnindex);例如:prepareStatement.setInt(colomnindex); In the same way is there any pre-defined method to add image to DataBase?同样,是否有任何预定义的方法将图像添加到数据库?

Something like this像这样的东西

HTML / JSP HTML / JSP

< input type="file" name="foto" /> < input type="file" name="foto" />

Serlvet塞尔维特

String fotoURL = req.getParameter("foto");
        System.out.println(fotoURL);
        URL urlFoto = null;
        urlFoto = getClass().getClassLoader().getResource(fotoURL); 


        System.out.println(urlFoto);
        BufferedImage foto = ImageIO.read(urlFoto);

Starting with, select a file for upload using JSP you need at least a HTML element which will display a file browse field.首先,使用 JSP 选择要上传的文件,您至少需要一个 HTML 元素来显示文件浏览字段。

<form action="upload" method="post" enctype="multipart/form-data">
   <input type="file" name="file">
   <input type="submit">
</form>

to retrieve the uploaded file inside servlet,在servlet中检索上传的文件,

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
   if (!item.isFormField()) {
    // <input type="file">
    System.out.println("Field name: " + item.getFieldName());
    System.out.println("File name: " + item.getName());
    System.out.println("File size: " + item.getSize());
    System.out.println("File type: " + item.getContentType());
  } else {
    // <input type="text|submit|hidden|password|button">, <select>, <textarea>,<button>
    System.out.println("Field name: " + item.getFieldName());
    System.out.println("Field value: " + item.getString());
  }              
 }

You just need to get the InputStream from the FileItem object and write it to any OutputStream.您只需要从 FileItem 对象获取 InputStream 并将其写入任何 OutputStream。

   InputStream content = item.getInputStream();
                     OR
   item.write(new File("/uploads/filename.ext"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM