java里的图片上传回显方法

java里的图片上传回显方法

 

整体流程:

         在前端页面中通过input标签的type属性值为file方式上传文件,通过ajax异步提交的方式实现页面里图片的实时显示。后台采用servlet方式,判断前端页面的提交数据的方式(post或者get方式),获取数据信息

 

 

准备:

jar包 准备:一个commons-io-2.6.jar包,一个commons-fileupload-1.3.3.jar包

        

         Js准备:ajaxfileupload.js (js异步提交所需要的js)

        

 

Jsp代码:      

   <form action="demo" method="post">

          <div id="file">

         

               <button type="button" onclick="deleteImg()">删除</button>

              

               <span id="span">

                    +

               </span>

               <input id="firstImg" type="hidden" name="firstImg" value="">

               <input id="myFile" type="file" name="myFile" onchange="uploadImg(this)"/>

          </div>

          <input type="submit" >

     </form>



创建uploadImg()事件

function uploadImg(obj){

               var id = obj.id;

               $.ajaxFileUpload({

                    fileElementId:id,

                    url:'demo',

                    type:'POST',

                    dataType:'text',

                    success:function(data){

                         if(data!=null || data.trim()!=""){

$("#span").html("<img src='"+data+"' width='200px' height='200px'>");

                              $("#firstImg").val(data);

                         }

                    }

              

               });

          }

 

 

发送ajaxFileUpload()请求,后台servlet接收请求,上传图片,页面会动态获取图片信息,将文件保存到指定的路径文件夹去。

后台servl代码:

@Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)

            throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");

        resp.setContentType("text/html;charset=utf-8");

        //获取系统中图片存储的路径

        String url = "img/";

        String path = getServletContext().getRealPath("/"+url);

        System.out.println("path:"+path);

        //1、创建文件工厂对象

        DiskFileItemFactory factory = new DiskFileItemFactory();

        //2、创建文件解析器对象

        ServletFileUpload sfu = new ServletFileUpload(factory);

        try {

            //3、通过解析器,获取上传文件的集合

            List<FileItem> fileItemList = sfu.parseRequest(req);

            //遍历集合

            FileItem fileItem = fileItemList.get(0);

            String fileName = new Date().getTime()+"_"+fileItem.getName();

            System.out.println("fileName:"+fileName);

            //设置文件的保存对象

            File file = new File(path+fileName);

            System.out.println("file:"+file);

            //保存文件

            fileItem.write(file);

            resp.getWriter().print(url+fileName);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

 

 

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的 Java Web 图片上传回显JSP 和 Servlet 完整代码示例。 JSP 页面代码(upload.jsp): ```jsp <!DOCTYPE html> <html> <head> <title>图片上传回显</title> </head> <body> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="上传"> </form> <% if (request.getAttribute("imageUrl") != null) { %> <img src="<%= request.getAttribute("imageUrl") %>"> <% } %> </body> </html> ``` Servlet 代码(UploadServlet.java): ```java import java.io.File; import java.io.IOException; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/upload") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String UPLOAD_DIR = "uploads"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String applicationPath = request.getServletContext().getRealPath(""); String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR; File fileSaveDir = new File(uploadFilePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdirs(); } Part part = request.getPart("image"); String fileName = UUID.randomUUID().toString() + "_" + part.getSubmittedFileName(); String filePath = uploadFilePath + File.separator + fileName; part.write(filePath); String imageUrl = request.getContextPath() + "/" + UPLOAD_DIR + "/" + fileName; request.setAttribute("imageUrl", imageUrl); request.getRequestDispatcher("upload.jsp").forward(request, response); } } ``` 注意事项: - 在 JSP 中,当检查请求属性 "imageUrl" 是否存在时,请使用 `request.getAttribute("imageUrl") != null`。 - 在 Servlet 中,将上传的文件保存到服务器上的路径可以使用 `request.getServletContext().getRealPath("")` 获取当前应用程序的根目录。 - 在 Servlet 中,获取上传的文件的文件名可以使用 `part.getSubmittedFileName()` 方法。 - 在 Servlet 中,通过 `request.getContextPath()` 获取应用程序的上下文路径,例如 "/myapp"。 - 在 Servlet 中,使用 `request.getRequestDispatcher("upload.jsp").forward(request, response)` 转发回 JSP 页面,并在 JSP 页面中显示上传的图片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我是王小贱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值