Ajax应用之文件上传

前端之家收集整理的这篇文章主要介绍了Ajax应用之文件上传前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

文件上传是一个很费时的任务,经常需要用户进行长时间等待,为了让用户在等待过程中,及时了解上传进度,可以在进行文件上传时,显示上传进度条。示例:

index.jsp:

<%@ page language="java" import="java.util.*"
	contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script language="JavaScript" src="JS/AjaxRequest.js"></script>

<script language="JavaScript">

	//处理文件上传
	function deal(form) {
		form.submit();
		window.setInterval("getProgress()",500);
	}

	//获取进度方法
	function getProgress() {
		var loader = new net.AjaxRequest("showProgress.jsp?nocache="
				+ new Date().getTime(),dealProgress,onerror,"GET");
	}
	
	//处理获取进度结果
	function dealProgress() {
		var h = this.req.responseText;
		h=h.replace("^s/g","");
		document.getElementById("progressPercent").style.display="";
		document.getElementById("progressPercent").innerHTML=h+"%";
		document.getElementById("progressBar").style.display="block";
		document.getElementById("imgProgress").width=h*(255/100);
	}

	function onerror() {
		alert("文件上传出错!");
	}
</script>
<title>起始页</title>
</head>
<body>
	<form method="post" action="UploadServlet?action=uploadFile"
		name="form1" enctype="multipart/form-data">
		请选择上传文件:<input name="file" type="file" size="42"> <img
			src="images/upload.jpg" width="61" height="23" onclick="deal(form1)">
	</form>
	<div id="progressBar" class="progressBar" align="left">
		<img src="images/progressBar.jpg" width="0" height="13"
			id="imgProgress">
	</div>
	<span id="progressPercent" style="width: 40px; display: none;">0%</span>
</body>
</html>


UploadServlet:
package com.home.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
@MultipartConfig(location = "e:/tmp")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,IOException {
        uploadFile(request,response);
	}

    public void uploadFile(HttpServletRequest request,IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        session.setAttribute("progressBar",0);
        String error = "";
        int maxSize = 50 * 1024 * 1024;
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator it = items.iterator();
            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (!"".equals(item.getName()) && item.getName() != null) {
                        long upFileSize = item.getSize();
                        String fileName = item.getName();
                        if (upFileSize > maxSize) {
                            error = "文件不能超过50M";
                            break;
                        }
                        File tempFile = new File(fileName);
                        File file = new File(request.getRealPath("/upload"),tempFile.getName());
                        System.out.println(file.getAbsolutePath());
                        InputStream is = item.getInputStream();
                        int len = 0;
                        byte[] b = new byte[1024];
                        double percent = 0;
                        FileOutputStream fos = new FileOutputStream(file);
                        while ((len = is.read(b)) != -1) {
                            percent += len / (double) upFileSize * 100D;
                            fos.write(b,len);
                            session.setAttribute("progressBar",Math.round(percent));
                        }
                        fos.close();
                        Thread.sleep(1000);
                    } else {
                        error = "没有选择上传文件";
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            error = "文件上传出现错误:" + e.getMessage();
        }
        if (!"".equals(error)) {
            request.setAttribute("error",error);
            request.getRequestDispatcher("error.jsp").forward(request,response);
        } else {
            request.setAttribute("result","文件上传成功!");
            request.getRequestDispatcher("result.jsp").forward(request,response);
        }
    }


}

showProgress.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	${progressBar}
</body>
</html>

猜你在找的Ajax相关文章