【问题标题】:I upload images with html form but I can't visualise them once displayed with the servlet我用 html 表单上传图像,但一旦用 servlet 显示,我就无法将它们可视化
【发布时间】:2021-06-19 05:22:21
【问题描述】:

该任务需要上传带有 html 表单的图像并使用 servlet 将其发送回来。

这是表单代码:

'''

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel='stylesheet'  href='styles.css'>
        <title>What's new?</title>
    </head>
    <body>
        <div class="flex-container-col">
        <form class="basic_form" action="Servlet2" method="post" enctype="multipart/form-data">
            <fieldset>
                <label class="form_labels">Post something new</label>
                <br>
                <input type="file" name="file"/>
                <br><br>
                <textarea name='newstatement' rows=5 cols=50>Type here...
                </textarea>
                <div class="flex-container-col">
                    <input class="form_buttons" type="submit" value="Submit">
                </div>
            </fieldset>
        </form>
        </div>      
    </body>
</html>

'''

这是 servlet 之一:

'''

@WebServlet(name = "Servlet2", urlPatterns = {"/Servlet2"})
@MultipartConfig
public class Servlet2 extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            
            Part part = request.getPart("file");
            String fileName = part.getSubmittedFileName();
            
            String path = getServletContext().getRealPath("/"+"media"+File.separator+fileName);

            InputStream is = part.getInputStream();
            
            boolean succs = UploadFile(is, path);
            if(succs){
                out.println("file uploaded to this directory: "+path);
                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet Servlet1</title>");            
                out.println("</head>");
                out.println("<body>");
                out.println("<img src=\"media/"+fileName+" alt=\"\" \n"+">");
                out.println("</body>");
                out.println("</html>"); 
            }
            else{
                out.println("error");
            }
        }
    }
    
    public boolean UploadFile(InputStream is, String path) {
        boolean test = false;
        
        try{
            byte[] byt = new byte[is.available()];
            is.read();
            FileOutputStream fops = new FileOutputStream(path);
            fops.write(byt);
            fops.flush();
            fops.close();
            
            test = true;
            
        }catch(Exception e){
            e.printStackTrace();
        }
        
        return test;
    }

    

}

'''

问题是,当我上传图片时,我看不到它的显示: enter image description here

但我只将其视为一个小图标。转到我保存它的文件夹,我看到: enter image description here

【问题讨论】:

    标签: java html jsp servlets netbeans


    【解决方案1】:

    上传图片的字节永远不会被读取:

    is.read() 返回 InputStream 上的下一个可用字节,但代码没有捕获它(就像在 int b = is.read() 中一样。

    您似乎还计划创建一个足够大的缓冲区以容纳所有字节 (byt),可能与 is.read(byt) 一起使用,但这不能保证工作,因为 is.available() 可能不会返回完整InputStream 的长度,正如InputStream.available() 的文档所述:

    使用这个方法的返回值来分配一个缓冲区来保存这个流中的所有数据是不正确的。

    类似

    byte[] buffer = new byte[1024];
    while (-1 != (bytesRead = is.read(buffer))) {
       fops.write(buffer, 0, bytesRead);
    }
    

    可能会起作用,但何必呢?只需使用Files.copy

    Path nioPath = FileSystems.getDefault().getPath(path);
    Files.copy(is, nioPath, StandardCopyOption.REPLACE_EXISTING);
    

    让图书馆做这项工作。

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2011-11-26
      • 2020-04-18
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多