`

ajax upload 实现文件上传

阅读更多

Ajax Upload; A file upload script with progress-bar, drag-and-drop .

 

An older ajax upload plugin, which only used iframe for uploads, and was licensed under MIT license is located on github. This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere. Demo To upload a file, click on the button below. Drag-and-drop is supported in FF, Chrome. Progress-bar is supported in FF3.6+, Chrome6+, Safari4+

 

More info please refer: valums.com/ajax-upload/

 

这是一个比较好的插件,前端和后端都有实现。前端javascript ajax,后端支持 java 和 php,其他的语言应该也可以支持,但是需要自己实现文件接收。

 

1。 server端 接收文件的 servlet:

 

/*
 *  Copyright 2010 Blue Lotus Software, LLC.
 *  Copyright 2010 John Yeary <jyeary@bluelotussoftware.com>.
 *  Copyright 2010 Allan O'Driscoll
 *
 * Dual Licensed MIT and GPL v.2 
 *
 * The MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 *
 * The GNU General Public License (GPL) Version 2, June 1991
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; version 2 of the License.

 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package com.bluelotussoftware.apache.commons.fileupload.example;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

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

import org.apache.commons.io.IOUtils;

import wavefancy.Utilities;

/**
 * Reads an <code>application/octet-stream</code> and writes it to a file.
 * @author John Yeary <jyeary@bluelotussoftware.com>
 * @author Allan O'Driscoll
 * @version 1.0
 */
public class OctetStreamReader extends HttpServlet {

    private static final long serialVersionUID = 6748857432950840322L;
    private static final String DESTINATION_DIR_PATH = "userImg";
    private static String realPath;

    /**
     * {@inheritDoc}
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH) + "/";
//          realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH); 
//          realPath = realPath.substring(0, realPath.length()-5)+"/userImg/";
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {
//    	System.out.println("Here!");
    	
        PrintWriter writer = null;
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            writer = response.getWriter();
        } catch (IOException ex) {
            log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
        }
        
        
        String filename = request.getHeader("X-File-Name");
        
        String tempFileName = Long.toString(System.currentTimeMillis()) + filename.substring(filename.lastIndexOf('.'));
        
        //result map
        Map<String, String> reMap = new HashMap<String, String>();
        
        try {
            is = request.getInputStream();
//            System.out.println(realPath); 
            
            File tempFile = new File(realPath+tempFileName);
            
            System.out.println(tempFile.getPath());
            fos = new FileOutputStream(tempFile);

            IOUtils.copy(is, fos);
            response.setStatus(HttpServletResponse.SC_OK);
            
            //store temp image file into httpSession, we will crop it according to user's parameters.
            HttpSession httpSession = request.getSession(true);
            httpSession.setAttribute("tempImg", tempFile);
            
            reMap.put("success", "true");
            reMap.put("tempImg", tempFile.getName());
            writer.print(Utilities.getRawGson().toJson(reMap));
//            writer.print("{success: true}");
        } catch (FileNotFoundException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            reMap.put("success", "false");
            writer.print(Utilities.getRawGson().toJson(reMap));
//            writer.print("{success: false}");
            log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
        } catch (IOException ex) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            reMap.put("success", "false");
            writer.print(Utilities.getRawGson().toJson(reMap));
//            writer.print("{success: false}");
            log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage());
        } finally {
            try {
                fos.close();
                is.close();
            } catch (IOException ignored) {
            }
        }
//        System.out.println("Done!");
        writer.flush();
        writer.close();
    }
}

 

2。web.xml 配置:

 

	  <servlet>
	     <servlet-name>ImgUpload</servlet-name>
	     <servlet-class>com.bluelotussoftware.apache.commons.fileupload.example.OctetStreamReader</servlet-class>
	  </servlet>
	    <servlet-mapping>
	     <servlet-name>ImgUpload</servlet-name>
	     <url-pattern>/imgUpload.do</url-pattern>
	  </servlet-mapping>

 

3。 web 前端调用

 

<head>
	<!--for file upload-->
	<script src="javascript/fileUploadClient/fileuploader.js"></script>
	<link rel="stylesheet" href="javascript/fileUploadClient/fileuploader.css" />
	<!--end for file upload-->
</head>

 

<head>
<script>
			//------------------ for file upload ----------------
		function createUploader(){            
            var uploader = new qq.FileUploader({
                element: document.getElementById('file-uploader-demo1'),
                action: 'imgUpload.do',
                debug: false,
				allowedExtensions:['jpg','jpeg','png','gif'],
				sizeLimit: 5000000, //5m
				minSizeLimit: 1000, //1k
				onComplete: function(id, fileName, responseJSON){

//					alert(responseJSON.tempImg);
					
					$("#target").attr("src","userImg/"+responseJSON.tempImg);
					$("#preview").attr("src","userImg/"+responseJSON.tempImg);
					
					$("#stepTwo").css({
						display:'block'
					});
					//fire jcrop
					fireJcrop();
					
				}
            });           
        }
        
        // in your app create uploader as soon as the DOM is ready
        // don't wait for the window to load  
        window.onload = createUploader;     
		//--------------------end for file upload----------------------	

</script>
</head>
 

 

 

<body>
		<div id="file-uploader-demo1" style="margin-left:20px;">		
			<noscript>			
				<p>Please enable JavaScript to use file uploader.</p>
				<!-- or put a simple form for upload here -->
			</noscript>         
	    </div>
</body>
分享到:
评论

相关推荐

    Jquery AjaxUpload实现文件上传实例 PHP版

    在这个“Jquery AjaxUpload实现文件上传实例 PHP版”中,我们将探讨如何使用jQuery的AjaxUpload插件与PHP后端进行配合,实现实时的文件上传功能。 首先,我们需要在HTML页面中创建一个用于选择文件的input元素和一...

    Jquery AjaxUpload实现文件上传功能代码

    随着WEB技术的发展,用户体验成为衡量网站成功与否的关键,今天和大家分享如何在PHP中利用Jquery实现Ajax方式文件上传功能的例子,其中使用到了Jquery插件Ajaxupload,其可以实现单个文件和多文件上传功能。

    ajaxupload无刷新文件上传,支持多文件上传,使用很方便哦

    ajaxupload.js 是一款使用jquery上传文件的js插件,对于简单的文件上传,足够可以应付, 你可以根据自身需要对前后端代码进行补充,也可以将一些...总的来说Jquery插件AjaxUpload实现文件上传功能的应用还是比较容易的。

    jquery插件ajaxupload实现文件上传操作

    本文实例讲述了jquery插件ajaxupload实现文件上传操作代码。分享给大家供大家参考。具体如下: 运行效果截图如下: 图1 文件上传前 图2 文件上传后 具体代码如下: 1、创建页面并编写HTML 上传文档:  ...

    AjaxUpload.rar 文件上传

    AjaxUpload是一种基于JavaScript和Ajax技术实现的异步文件上传方式,它允许用户在不刷新整个网页的情况下上传文件,显著提升了用户体验。AjaxUpload的核心是利用XMLHttpRequest对象与服务器进行交互,通过创建隐藏的...

    Base64和AjaxUpload上传文件代码实例

    Base64和AjaxUpload上传文件代码实例是两种常用的文件上传方式,它们都可以实现文件上传到服务器端,但它们之间有着明显的区别。 Base64上传文件是一种基于文本编码的上传方式,它将文件转换为Base64字符串,然后将...

    AjaxUpLoad.js实现文件上传功能

    在使用AjaxUpLoad.js实现无刷新文件上传的过程中,服务器端也需要做一些处理。由于这里的描述并没有具体提供服务器端的代码和处理逻辑,但是通常,服务器端需要接收通过AJAX上传的文件数据,并进行存储。服务器端...

    ssm整合+ajaxUpload文件上传

    AjaxUpload则是实现异步文件上传的一种JavaScript库,它允许用户在不刷新整个页面的情况下进行文件上传,提高了用户体验。接下来,我们将详细讨论这两个知识点。 首先,**Spring** 是一个全面的后端应用框架,它...

    Ajax Upload多文件上传插件

    Ajax Upload文件上传插件允许你上传多个插件而无需刷新页面,可以使用任何的元素来显示文件选择窗口。它可以在所有主流的浏览器下工作,从2.0版本开始,不需要任何库运行。Ajax Upload文件上传插件不会污染任何命名...

    Python - Flask 使用Ajax 实现多文件上传

    以下将详细介绍如何在Flask中利用Ajax实现多文件上传。 **一、Flask基础知识** Flask是一个轻量级的Web服务程序,它使用Python编写,基于Werkzeug WSGI工具箱和Jinja2模板引擎。Flask提供了一个简单易用的接口,...

    ajaxupload在spring mvc4.2中实现简单文件上传

    在Spring MVC 4.2框架中实现AjaxUpload(异步文件上传)是一个常见的需求,它允许用户在不刷新整个页面的情况下进行文件上传,提供更好的用户体验。以下是对这一主题的详细阐述: 1. **AjaxUpload简介**: Ajax...

    ajaxupload.js

    AjaxUpload是一种在Web应用中实现异步文件上传的技术,它基于JavaScript的Ajax(Asynchronous JavaScript and XML)技术,允许用户在不刷新整个页面的情况下上传文件,提高了用户体验。`ajaxupload.js`是实现这一...

    使用ajaxupload.js/ajaxfileupload.js实现文件上传

    `ajaxupload.js` 和 `ajaxfileupload.js` 是两个用于实现异步文件上传的JavaScript库,它们简化了这个过程并提供了丰富的自定义选项。 首先,`ajaxupload.js` 是一个轻量级的插件,它扩展了传统的Ajax功能,允许...

    ajaxupload.js上传图片

    1. **异步上传**:AjaxUpload.js 使用XMLHttpRequest对象(即Ajax)来创建非阻塞的文件上传请求。这意味着当用户选择一个文件并触发上传时,浏览器不会立即跳转或刷新页面。 2. **事件处理**:在上传过程中,Ajax...

    ajax实现文件上传

    ### AJAX 实现文件上传 在探讨 AJAX 如何实现文件上传之前,我们首先简要回顾一下 AJAX 的历史背景及其带来的变革。AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分...

    jquery Ajaxupload应用

    AjaxUpload是一款基于jQuery的插件,它通过异步方式实现文件上传,避免了传统文件上传时整个页面刷新的问题。这种技术依赖于HTML5的FormData对象(对于不支持HTML5的浏览器,它会退回到IFrame上传),提供了一种优雅...

    ajaxupload华丽的图片上传

    利用ajaxupload组件实现的图片上传 1、在部署该工程时,要在tomcat/webapps/对应的工程下建upload/good目录; 2、在该工程中,点击一次上传图片按钮,就执行一次后台操作,然后将图片的路径保存在一个input的隐藏域...

    Ajax实现文件上传

    本文将详细探讨如何使用Ajax实现文件上传,并特别关注文件上传进度条的实现。 一、Ajax基础 Ajax,全称Asynchronous JavaScript and XML,是一种创建动态网页的技术。通过在后台与服务器进行少量数据交换,Ajax可以...

    ajaxUpload.

    标题"ajaxUpload."和描述"ajaxUpload.ajaxUpload.ajaxUpload."暗示我们将深入探讨这个话题。 ### 一、Ajax Upload原理 Ajax Upload的核心是利用JavaScript的异步特性,通过XMLHttpRequest对象与服务器进行通信。它...

Global site tag (gtag.js) - Google Analytics