JQuery Ajax File Upload

1、HTML

 ======================================测试部分==========================================
       						 <img src="${pageContext.request.contextPath}/img/loading.gif" id="loading" style="display: none;">
					        <table class="tableForm">  
					            <thead>  
					                <tr>  
					                    <th>JQuery Ajax File Upload</th>  
					                </tr>  
					            </thead>  
					            <tbody>  
					                <tr>  
					                    <td><input id="fileToUpload"  type="file" size="45"   
					                        name="fileToUpload"  class="input"></td>  
					                </tr>  
					            </tbody>  
					            <tfoot>  
					                <tr>  
					                    <td><button class="button" id="buttonUpload"  
					                            onclick="ajaxFileUpload();">Upload</button></td>  
					                </tr>  
					            </tfoot>  
					        </table>  
					        <div id="result" style="margin-left:200px"></div>  
					    <!-- upload file end -->
					    ================================================================================

 

 

 

2、js

  <script src="${pageContext.request.contextPath}/js/jquery.js"></script>
  <script src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></script>

function ajaxFileUpload() {  
  			$("#loading").ajaxStart(function(){
  	            $(this).show();
  	        })//开始上传文件时显示一个图片
  	        .ajaxComplete(function(){
  	            $(this).hide();
  	        });//文件上传完成将图片隐藏起来
  	        
  		    $.ajaxFileUpload({  
  		        url : "../UploadPhoto",   //submit to UploadFileServlet  
  		        secureuri : false,  
  		        fileElementId : 'fileToUpload',  
  		        dataType : 'json', //or json xml whatever you like~  
  		        success : function(data, status) { 
  		        	alert('success data : ' + data.message);
  		        	$('#test').html(data.message);
  		        	if(typeof(data.error) != 'undefined')
                    {
                        if(data.error != '')
                        {
                            //alert(data.error);
                            $('#test').html(data.message);
                        }else
                        {
                            //alert(data.message);
                            $('#test').html(data.message);
                        }
                    }
  		        },  
  		        error : function(data, status, e) {  
  		        }  
  		    });
  		}  

 

 

3、servlet

package com.pmis.user.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 上传文件 处理servlet
 */
public class UploadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = LoggerFactory.getLogger(UploadFileServlet.class);

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");
		// 判断提交过来的表单是否为文件上传菜单
	
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
	    // 设置字符编码为UTF-8, 这样支持汉字显示
	    response.setCharacterEncoding("UTF-8");
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        PrintWriter writer = response.getWriter();
        JSONArray json = new JSONArray();
		String result = "";
		if (isMultipart) {
			// 构造一个文件上传处理对象
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);

			Iterator items;
			try {
				// 解析表单中提交的所有文件内容
				items = upload.parseRequest(request).iterator();
				while (items.hasNext()) {
					FileItem item = (FileItem) items.next();
					if (!item.isFormField()) {
						// 取出上传文件的文件名称
						String name = item.getName();
						// 取得上传文件以后的存储路径
						String fileName = name.substring(name.lastIndexOf('\\') + 1, name.length());
						// 上传文件以后的存储路径
						String saveDir = this.getServletContext().getRealPath("/upload/");
						if (!(new File(saveDir).isDirectory())) {
							new File(saveDir).mkdir();
						}
						String path = saveDir + File.separatorChar + fileName;
						result = File.separatorChar + fileName;
						// 上传文件
						File uploaderFile = new File(path);
						
						long size = item.getSize();
				        if ("".equals(path) || size == 0) {
							result = "{message:'请选择上传文件'}";
				            return;
				        }

				        String t_name = path.substring(path.lastIndexOf("\\") + 1);
				        // 得到文件的扩展名(无扩展名时将得到全名)
				        String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1).toLowerCase();
				        if(!"jpg".endsWith(t_ext) && !"jpeg".endsWith(t_ext)) {
				        	result = "{message:'请选择上传jpg/jpeg格式图片'}";
				            return;
				        }
						item.write(uploaderFile);
			        	result = "{message:'ok',url:'upload/" + fileName + "'}";
						
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				 //writer.write(json.toString());
				 writer.write(result);
                 writer.close();
			}
		}
	}
}

 

你可能感兴趣的:(jQuery ajax)