jsp中上传图片(使用ajaxfileupload)

一世执手 提交于 2019-12-30 10:10:08

jsp中无刷新上传图片(前台使用jquery+ajaxfileupload),后台用commons-fileupload处理


需求:前台选择图片,页面显示上传后的图片地址


代码一:ajaxUploadImg.jsp

请百度搜索,并下载jquery.js 及 ajaxfileupload.js

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
<%  
    String path = request.getContextPath();  
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path + "/";  
%>  
  
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
<html>  
  <head>  
    <base href="<%=basePath%>">  
    <meta http-equiv="pragma" content="no-cache">  
    <meta http-equiv="cache-control" content="no-cache">  
    <meta http-equiv="expires" content="0">      
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="This is my page">  
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    -->  
    <script language="javascript" src="<%=basePath%>js/jquery.js" ></script>  
    <script language="javascript" src="<%=basePath%>js/ajaxfileupload.js" > </script>   
    <script language="javascript" type="text/javascript" src="<%=basePath%>js/ezeditor.js"></script>  
    <script type="text/javascript">  
    function ajaxFileUpload()  
    {  
      
    $("#loading")  
        .ajaxStart(function(){  
            $(this).show();  
        })//开始上传文件时显示一个图片  
        .ajaxComplete(function(){  
            $(this).hide();  
        });//文件上传完成将图片隐藏起来  
          
       $.ajaxFileUpload({  
                 url:'<%=basePath %>FileUpload',             //需要链接到服务器地址  
                 secureuri:false,  
                 fileElementId:'uploadFileInput',                         //文件选择框的id属性  
                 dataType: 'json',                                     //服务器返回的格式,可以是json  
                 success: function (data, status)             //相当于java中try语句块的用法  
                 {     
                 //alert(data);       //data是从服务器返回来的值     
                     $('#result').html('上传图片成功!请复制图片地址<br/>'+data.src);  
   
                 },  
                 error: function (data, status, e)             //相当于java中catch语句块的用法  
                 {  
                     $('#result').html('上传图片失败');  
                 }  
               }  
             );  
    }  
    </script>  
  </head>  
    
  <body>   
  <div id="result" style="FONT:12px 宋体"></div><br/>  
 <img id="loading" src="loading.gif" style="display:none;">  
        <form name="form_uploadImg" action="" method="POST" enctype="multipart/form-data">  
 <input id="uploadFileInput" type="file" size="45" name="uploadFileInput" class="input" />  
 <input type="button" id="buttonUpload" onclick="return ajaxFileUpload();" value="上传图片"/>  
 </form>  
</html

代码二: FileUpload.java
这里使用了commons-fileupload-1.2.1.jar的包,可以自行搜索下载
如果使用myeclipse,可以直接在Struts 2 Core Libraies中找到.
commons-fileupload-1.2.1.jar

    package com.lz.servlet;  
      
    import java.io.BufferedInputStream;  
    import java.io.BufferedOutputStream;  
    import java.io.File;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.util.Date;  
    import java.util.regex.Matcher;  
    import java.util.regex.Pattern;  
      
    import javax.servlet.ServletException;  
    import javax.servlet.http.HttpServlet;  
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpServletResponse;  
      
    import org.apache.commons.fileupload.FileItemIterator;  
    import org.apache.commons.fileupload.FileItemStream;  
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
    import org.apache.commons.fileupload.servlet.ServletFileUpload;  
    import org.apache.commons.fileupload.util.Streams;  
      
    public class FileUpload extends HttpServlet {  
      
        public FileUpload() {  
            super();  
        }  
      
        public void destroy() {  
            super.destroy();   
        }  
        public void doGet(HttpServletRequest request, HttpServletResponse response)  
                throws ServletException, IOException {  
      
        }  
      
        public void doPost(HttpServletRequest request, HttpServletResponse response)  
                throws ServletException, IOException {  
            response.setContentType("text/html");     
            response.setCharacterEncoding("UTF-8");  
            String realDir = request.getSession().getServletContext().getRealPath("");  
            String contextpath = request.getContextPath();  
            String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + contextpath + "/";  
      
            try {  
            String filePath = "uploadfiles";  
            String realPath = realDir+"\\"+filePath;  
            //判断路径是否存在,不存在则创建  
            File dir = new File(realPath);  
            if(!dir.isDirectory())  
                dir.mkdir();  
      
            if(ServletFileUpload.isMultipartContent(request)){  
      
                DiskFileItemFactory dff = new DiskFileItemFactory();  
                dff.setRepository(dir);  
                dff.setSizeThreshold(1024000);  
                ServletFileUpload sfu = new ServletFileUpload(dff);  
                FileItemIterator fii = null;  
                fii = sfu.getItemIterator(request);  
                String title = "";   //图片标题  
                String url = "";    //图片地址  
                String fileName = "";  
                String state="SUCCESS";  
                String realFileName="";  
                while(fii.hasNext()){  
                    FileItemStream fis = fii.next();  
      
                    try{  
                        if(!fis.isFormField() && fis.getName().length()>0){  
                            fileName = fis.getName();  
                            Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");  
                            Matcher matcher=reg.matcher(fileName);  
                            if(!matcher.find()) {  
                                state = "文件类型不允许!";  
                                break;  
                            }  
                            realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length());  
                            url = realPath+"\\"+realFileName;  
      
                            BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流  
                            FileOutputStream a = new FileOutputStream(new File(url));  
                            BufferedOutputStream output = new BufferedOutputStream(a);  
                            Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹  
                        }else{  
                            String fname = fis.getFieldName();  
      
                            if(fname.indexOf("pictitle")!=-1){  
                                BufferedInputStream in = new BufferedInputStream(fis.openStream());  
                                byte c [] = new byte[10];  
                                int n = 0;  
                                while((n=in.read(c))!=-1){  
                                    title = new String(c,0,n);  
                                    break;  
                                }  
                            }  
                        }  
      
                    }catch(Exception e){  
                        e.printStackTrace();  
                    }  
                }  
                response.setStatus(200);  
                String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',status:success}";  
                response.getWriter().print(retxt);  
            }  
            }catch(Exception ee) {  
                ee.printStackTrace();  
            }  
              
        }  
        public void init() throws ServletException {  
            // Put your code here  
        }  
      
    }  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!