ajaxfileupload上传

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


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


代码一:ajaxUploadImg.jsp

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

[html]  view plain  copy
 print ?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.   <head>  
  12.     <base href="<%=basePath%>">  
  13.     <meta http-equiv="pragma" content="no-cache">  
  14.     <meta http-equiv="cache-control" content="no-cache">  
  15.     <meta http-equiv="expires" content="0">      
  16.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  17.     <meta http-equiv="description" content="This is my page">  
  18.     <!-- 
  19.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  20.     -->  
  21.     <script language="javascript" src="<%=basePath%>js/jquery.js" ></script>  
  22.     <script language="javascript" src="<%=basePath%>js/ajaxfileupload.js" > </script>   
  23.     <script language="javascript" type="text/javascript" src="<%=basePath%>js/ezeditor.js"></script>  
  24.     <script type="text/javascript">  
  25.     function ajaxFileUpload()  
  26.     {  
  27.       
  28.     $("#loading")  
  29.         .ajaxStart(function(){  
  30.             $(this).show();  
  31.         })//开始上传文件时显示一个图片  
  32.         .ajaxComplete(function(){  
  33.             $(this).hide();  
  34.         });//文件上传完成将图片隐藏起来  
  35.           
  36.        $.ajaxFileUpload({  
  37.                  url:'<%=basePath %>FileUpload',             //需要链接到服务器地址  
  38.                  secureuri:false,  
  39.                  fileElementId:'uploadFileInput',                         //文件选择框的id属性  
  40.                  dataType: 'json',                                     //服务器返回的格式,可以是json  
  41.                  success: function (data, status)             //相当于java中try语句块的用法  
  42.                  {     
  43.                  //alert(data);       //data是从服务器返回来的值     
  44.                      $('#result').html('上传图片成功!请复制图片地址<br/>'+data.src);  
  45.    
  46.                  },  
  47.                  error: function (data, status, e)             //相当于java中catch语句块的用法  
  48.                  {  
  49.                      $('#result').html('上传图片失败');  
  50.                  }  
  51.                }  
  52.              );  
  53.     }  
  54.     </script>  
  55.   </head>  
  56.     
  57.   <body>   
  58.   <div id="result" style="FONT:12px 宋体"></div><br/>  
  59.  <img id="loading" src="loading.gif" style="display:none;">  
  60.         <form name="form_uploadImg" action="" method="POST" enctype="multipart/form-data">  
  61.  <input id="uploadFileInput" type="file" size="45" name="uploadFileInput" class="input" />  
  62.  <input type="button" id="buttonUpload" onclick="return ajaxFileUpload();" value="上传图片"/>  
  63.  </form>  
  64. </html>  

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


[java]  view plain  copy
 print ?
  1. package com.lz.servlet;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.util.Date;  
  9. import java.util.regex.Matcher;  
  10. import java.util.regex.Pattern;  
  11.   
  12. import javax.servlet.ServletException;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17. import org.apache.commons.fileupload.FileItemIterator;  
  18. import org.apache.commons.fileupload.FileItemStream;  
  19. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  20. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  21. import org.apache.commons.fileupload.util.Streams;  
  22.   
  23. public class FileUpload extends HttpServlet {  
  24.   
  25.     public FileUpload() {  
  26.         super();  
  27.     }  
  28.   
  29.     public void destroy() {  
  30.         super.destroy();   
  31.     }  
  32.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  33.             throws ServletException, IOException {  
  34.   
  35.     }  
  36.   
  37.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  38.             throws ServletException, IOException {  
  39.         response.setContentType("text/html");     
  40.         response.setCharacterEncoding("UTF-8");  
  41.         String realDir = request.getSession().getServletContext().getRealPath("");  
  42.         String contextpath = request.getContextPath();  
  43.         String basePath = request.getScheme() + "://"  
  44.         + request.getServerName() + ":" + request.getServerPort()  
  45.         + contextpath + "/";  
  46.   
  47.         try {  
  48.         String filePath = "uploadfiles";  
  49.         String realPath = realDir+"\\"+filePath;  
  50.         //判断路径是否存在,不存在则创建  
  51.         File dir = new File(realPath);  
  52.         if(!dir.isDirectory())  
  53.             dir.mkdir();  
  54.   
  55.         if(ServletFileUpload.isMultipartContent(request)){  
  56.   
  57.             DiskFileItemFactory dff = new DiskFileItemFactory();  
  58.             dff.setRepository(dir);  
  59.             dff.setSizeThreshold(1024000);  
  60.             ServletFileUpload sfu = new ServletFileUpload(dff);  
  61.             FileItemIterator fii = null;  
  62.             fii = sfu.getItemIterator(request);  
  63.             String title = "";   //图片标题  
  64.             String url = "";    //图片地址  
  65.             String fileName = "";  
  66.             String state="SUCCESS";  
  67.             String realFileName="";  
  68.             while(fii.hasNext()){  
  69.                 FileItemStream fis = fii.next();  
  70.   
  71.                 try{  
  72.                     if(!fis.isFormField() && fis.getName().length()>0){  
  73.                         fileName = fis.getName();  
  74.                         Pattern reg=Pattern.compile("[.]jpg|png|jpeg|gif$");  
  75.                         Matcher matcher=reg.matcher(fileName);  
  76.                         if(!matcher.find()) {  
  77.                             state = "文件类型不允许!";  
  78.                             break;  
  79.                         }  
  80.                         realFileName = new Date().getTime()+fileName.substring(fileName.lastIndexOf("."),fileName.length());  
  81.                         url = realPath+"\\"+realFileName;  
  82.   
  83.                         BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流  
  84.                         FileOutputStream a = new FileOutputStream(new File(url));  
  85.                         BufferedOutputStream output = new BufferedOutputStream(a);  
  86.                         Streams.copy(in, output, true);//开始把文件写到你指定的上传文件夹  
  87.                     }else{  
  88.                         String fname = fis.getFieldName();  
  89.   
  90.                         if(fname.indexOf("pictitle")!=-1){  
  91.                             BufferedInputStream in = new BufferedInputStream(fis.openStream());  
  92.                             byte c [] = new byte[10];  
  93.                             int n = 0;  
  94.                             while((n=in.read(c))!=-1){  
  95.                                 title = new String(c,0,n);  
  96.                                 break;  
  97.                             }  
  98.                         }  
  99.                     }  
  100.   
  101.                 }catch(Exception e){  
  102.                     e.printStackTrace();  
  103.                 }  
  104.             }  
  105.             response.setStatus(200);  
  106.             String retxt ="{src:'"+basePath+filePath+"/"+realFileName+"',status:success}";  
  107.             response.getWriter().print(retxt);  
  108.         }  
  109.         }catch(Exception ee) {  
  110.             ee.printStackTrace();  
  111.         }  
  112.           
  113.     }  
  114.     public void init() throws ServletException {  
  115.         // Put your code here  
  116.     }  
  117.   
  118. }  

代码三: web.xml做如下

[html]  view plain  copy
 print ?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  7.   <display-name></display-name>   
  8.   <welcome-file-list>  
  9.     <welcome-file>index.jsp</welcome-file>  
  10.   </welcome-file-list>  
  11.   
  12.   <servlet>  
  13.     <servlet-name>FileUpload</servlet-name>  
  14.     <servlet-class>com.lz.servlet.FileUpload</servlet-class>  
  15.   </servlet>  
  16.   
  17.   <servlet-mapping>  
  18.     <servlet-name>FileUpload</servlet-name>  
  19.     <url-pattern>/FileUpload</url-pattern>  
  20.   </servlet-mapping>  
  21. </web-app>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值