上传带有预览的图像

发布于 2024-08-15 20:10:32 字数 4438 浏览 2 评论 0原文

您好,我想使用 jsp 和 servlet 上传图像(以及其他表单详细信息)并预览它们。我能够完成上传部分,但无法了解如何在前端预览图像。

我正在使用 YUI 来实现它。实际上我正在尝试重用一个用 PHP 实现的示例。我在这里附上我的 Servlet 代码。上传完成后,将填充“completeFileName”。

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {            

            if(completeFileName == null) {
                PrintWriter pout = response.getWriter();
                JSONObject obj = new JSONObject();
                obj.put("hasError", new Boolean(true));
                pout.println(obj.toString());
            }
            try {

                OutputStream out = response.getOutputStream();
                Image image = Toolkit.getDefaultToolkit().getImage(completeFileName);
                ImageIcon icon = new ImageIcon(image);
                int height = icon.getIconHeight();
                int width = icon.getIconWidth();
  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                ImageIO.write(bi, "jpg", out);
                out.flush();                
            } catch (Exception ex) {

            }

我的 Jsp 代码如下所示:

<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/connection/connection.js"></script>
        <script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/utilities/utilities.js"></script>
        <script type="text/javascript">
            var $E = YAHOO.util.Event;
            var $  = YAHOO.util.Dom.get;
            var $D = YAHOO.util.Dom;
            function init(){
                var listImageHandler = {
                    success:function(o) {
                        var r = eval('(' + o.responseText + ')');
                        if(!r.hasError) {
                            var imageListCon = $('imageListCon');
                            var img = document.createElement('img');
                            //img.src = 'image.php?i=' + r.imageList[i];
                            img.src = r.fileName;
                            imageListCon.appendChild(img);
                        }
                    }
                };
                var onUploadButtonClick = function(e){
                    var uploadHandler = {
                        upload: function(o) {
                            //console.log(o.responseText);
                            $D.setStyle('indicator', 'visibility', 'hidden');
                            var r = eval('(' + o.responseText + ')');
                            if(r.hasError){
                                var errorString = '';
                                for(var i=0; i < r.errors.length; i++){
                                    errorString += r.errors[i];
                                }
                                alert(errorString);
                            }else{
                                YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
                            }
                        }
                    };
                    $D.setStyle('indicator', 'visibility', 'visible');
                    //the second argument of setForm is crucial,
                    //which tells Connection Manager this is an file upload form
                    YAHOO.util.Connect.setForm('testForm', true);
                    YAHOO.util.Connect.asyncRequest('POST', 'UploadFileServlet', uploadHandler);

                };
                $E.on('uploadButton', 'click', onUploadButtonClick);
                YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
            }

            $E.on(window, 'load', init);
        </script>        
    </head>
    <body>
        <form action="UploadFileServlet" method="POST" enctype="multipart/form-data" id="testForm">        
        <input type="file" name="testFile"><br>
        <input type="button" id="uploadButton" value="Upload"/>
        </form>
        <div class="restart"><a href="UploadFileServlet?redo=1">Redo It</a></div>
        <div  style="visibility:hidden; margin-bottom:1.5em;" id="indicator">Uploading... <img src="indicator.gif"/></div>
        <div id="imageListCon">

        </div>
    </body>

我无法获得响应,有人可以帮忙吗?

谢谢, 阿米特

Hi I wanted to upload images(along with other form details) and preview them, using jsp and servlets. I am able to do the uploading part but could not get, how to preview the images in the frontend.

I am using YUI to implement it. Actually I am trying to reuse an example which is implemented in PHP. I am attaching my Servlet code here. In this 'completeFileName' will be populated when a upload has been done.

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {            

            if(completeFileName == null) {
                PrintWriter pout = response.getWriter();
                JSONObject obj = new JSONObject();
                obj.put("hasError", new Boolean(true));
                pout.println(obj.toString());
            }
            try {

                OutputStream out = response.getOutputStream();
                Image image = Toolkit.getDefaultToolkit().getImage(completeFileName);
                ImageIcon icon = new ImageIcon(image);
                int height = icon.getIconHeight();
                int width = icon.getIconWidth();
  BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                ImageIO.write(bi, "jpg", out);
                out.flush();                
            } catch (Exception ex) {

            }

My Jsp code looks like this:

<script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/connection/connection.js"></script>
        <script type="text/javascript" src="http://yui.yahooapis.com/2.3.0/build/utilities/utilities.js"></script>
        <script type="text/javascript">
            var $E = YAHOO.util.Event;
            var $  = YAHOO.util.Dom.get;
            var $D = YAHOO.util.Dom;
            function init(){
                var listImageHandler = {
                    success:function(o) {
                        var r = eval('(' + o.responseText + ')');
                        if(!r.hasError) {
                            var imageListCon = $('imageListCon');
                            var img = document.createElement('img');
                            //img.src = 'image.php?i=' + r.imageList[i];
                            img.src = r.fileName;
                            imageListCon.appendChild(img);
                        }
                    }
                };
                var onUploadButtonClick = function(e){
                    var uploadHandler = {
                        upload: function(o) {
                            //console.log(o.responseText);
                            $D.setStyle('indicator', 'visibility', 'hidden');
                            var r = eval('(' + o.responseText + ')');
                            if(r.hasError){
                                var errorString = '';
                                for(var i=0; i < r.errors.length; i++){
                                    errorString += r.errors[i];
                                }
                                alert(errorString);
                            }else{
                                YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
                            }
                        }
                    };
                    $D.setStyle('indicator', 'visibility', 'visible');
                    //the second argument of setForm is crucial,
                    //which tells Connection Manager this is an file upload form
                    YAHOO.util.Connect.setForm('testForm', true);
                    YAHOO.util.Connect.asyncRequest('POST', 'UploadFileServlet', uploadHandler);

                };
                $E.on('uploadButton', 'click', onUploadButtonClick);
                YAHOO.util.Connect.asyncRequest('GET', 'UploadFileServlet', listImageHandler);
            }

            $E.on(window, 'load', init);
        </script>        
    </head>
    <body>
        <form action="UploadFileServlet" method="POST" enctype="multipart/form-data" id="testForm">        
        <input type="file" name="testFile"><br>
        <input type="button" id="uploadButton" value="Upload"/>
        </form>
        <div class="restart"><a href="UploadFileServlet?redo=1">Redo It</a></div>
        <div  style="visibility:hidden; margin-bottom:1.5em;" id="indicator">Uploading... <img src="indicator.gif"/></div>
        <div id="imageListCon">

        </div>
    </body>

I am unable to get the response, can anyone help in this please ?

Thanks,
Amit

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

<逆流佳人身旁 2024-08-22 20:10:32

由于安全限制,您无法在上传之前在前端预览图像

Due to security limitations, you cannot preview the image on the front-end prior to uploading

旧伤慢歌 2024-08-22 20:10:32

如果您已经能够将图像上传到服务器上的文件夹中,则可以使用页面中的图像控件轻松显示图像。将该文件夹设置为临时文件夹,您可能希望在上传完成后清空该文件夹。然后,您首先将文件上传到临时文件夹中并将其显示给用户。如果用户取消操作,则可以从文件夹中删除该文件。

但请记住,这并不是我们通常想象的真实图像预览。但由于这模仿了图像预览,因此它可能是一个选择。

If you are already able to upload the image in a folder at your server, you can easily display the image with a image control in your page. Let that folder be a temp folder which you may wish to empty after upload is completed. Then you first upload the file in the temp folder and display it to the user. If the user cancels the operation, you can delete the file from the folder.

But remember this will not be the real image preview as we generally visualize. But since this mimics the image preview, it may be a choice.

思念满溢 2024-08-22 20:10:32

我不了解 YUI,所以我无法详细介绍这一点,但我至少可以看出您的逻辑存在几个缺陷:您试图将图像的整个二进制内容写回到ajax回复。这是行不通的。在 HTML 中,您只能使用 元素显示图像,该元素的 src 属性应指向有效的 URL。例如:

<img src="/images/uploadedimage.jpg">

要实现此目的,只需将图像存储在本地磁盘文件系统或服务器端的数据库中,并在 ajax 响应中提供客户端可以访问图像的 URL。让 ajax 成功处理程序创建一个 DOM 元素 并用获取的 URL 填充其 src 值。

您需要创建一个 Servlet 来侦听此 URL,并通过 FileInputStream 从本地磁盘文件系统获取图像作为 InputStream 或通过 ResultSet#getBinaryStream() 从数据库中读取,并将其写入响应的 OutputStream 以及一组至少具有 content-type 的正确响应标头。您可以在此处找到此类 servlet 的示例。

也就是说,您确实不需要 Java 2D API。 ImageImageIcon 只会不必要地增加大量开销。只需将其作为 InputStream 获取,然后以通常的 Java IO 方式将其写入响应的 OutputStream 即可。

I don't know YUI, so I can't go in detail about this, but I can at least tell that there are several flaws in your logic: you're attempting to write the entire binary contents of the image back to the ajax response. This isn't going to work. In HTML you can only display images using an <img> element whose src attribute should point to a valid URL. Something like:

<img src="/images/uploadedimage.jpg">

To achieve this, just store the image at the local disk file system or a database at the server side and give in the ajax response the URL back with which the client can access the image. Let the ajax success handler create a DOM element <img> and fill its src value with the obtained URL.

You'll need to create a Servlet which listens on this URL and get the image as an InputStream from the local disk file system by FileInputStream or from the database by ResultSet#getBinaryStream() and writes it to the OutputStream of the response, along with a correct set of response headers with at least content-type. You can find here an example of such a servlet.

That said, you really don't need the Java 2D API for that. The Image and ImageIcon only unnecessarily adds much overhead. Just get it as an InputStream and write it the usual Java IO way to the OutputStream of the response.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文