zoukankan      html  css  js  c++  java
  • Java中利用ajaxfileupload.js组件实现文件的上传功能

    概要:

    在Java中,利用ajaxfileupload.js+commons-fileupload-1.3.1.jar 实现文件上传功能。

    关键字:

    Java,上传,ajaxfileupload,fileupload

    内容:

    进行Web方面的开发时,文件上传是经常会使用到的,所以如果能有一个简单、实用、性能良好的上传组件,我想是极好的,那么ajaxfileupload.js应该是个不错的选择,下面我就分享一次我的使用经验。

    这次文件上传的整个过程主要有一个Jsp文件、一个Java文件、一个Js文件组成,首先我们来看一下Jsp页面的代码:

    文件1:upload.jsp

    <input type="file" name="attachfiles" id="attachfiles" />
    <input type="button" value="点击上传" id="scbtn" />
    

    是的,你没有看错,jsp页面就只要这两行代码,接下来是js文件的代码。

    文件2:upload.js

    var basePath = null;
    $(function() {
        basePath = $("#basePath").attr("value");
        $("#scbtn").click(function() {
            ajaxFileUpload();
        });
    
    });
    // 文件上传
    function ajaxFileUpload() {
        $.ajaxFileUpload({
            url : basePath + "upload.ajax",// 用于文件上传的服务器端请求地址
            secureuri : false,// 一般设置为false
            fileElementId : 'attachfiles',// 文件上传控件的id属性
            dataType : 'json',// 返回值类型 一般设置为json
            enctype : "multipart/form-data",
            success : function(data, status) // 服务器成功响应处理函数
            {
            },
            error : function(data, status, e) {
            }
        });
        return false;
    }
    

    Js部分的代码主要是利用jQuery中发送ajax请求,访问后台的代码,那么接下来自然就是Java代码,你准备好了吗?

    文件3:UploadAjaxManager.java

    package org.4spaces.demo;
    import java.io.File;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.List;
    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.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    /**
     * 
     * @author 四个空格:https://www.4spaces.org
     * 
     */
    public class UploadAjaxManager extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            String uri = request.getRequestURI();
            int startIndex = uri.lastIndexOf("/") + 1;
            int endIndex = uri.lastIndexOf(".");
            String action = uri.substring(startIndex, endIndex);
            if (action.equals("upload")) {
                try {
                    request.setCharacterEncoding("UTF-8");
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
                DiskFileItemFactory fac = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(fac);
                upload.setHeaderEncoding("UTF-8");
                List<FileItem> fileList = new ArrayList<FileItem>();
                try {
                    fileList = upload.parseRequest(request);
                } catch (FileUploadException ex) {
                    ex.printStackTrace();
                }
                String targetPath = request.getSession().getServletContext()
                        .getRealPath("jsp/upload")
                        + "/";
                String fileName = "blank.doc";
                for (FileItem item : fileList) {
                    if (!item.isFormField()) {
                        fileName = item.getName();
                        File saveFile = new File(targetPath + fileName);
                        try {
                            item.write(saveFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
    

    当然,上面的代码一定不要忘记导包: commons-fileupload-1.3.1.jarcommons-io-2.4.jar.

    好了,有了上面的代码,你就可以轻松的实现上传文件了。

    PS:

    奉上完整的工程和代码的地址:工程源代码

  • 相关阅读:
    Git的使用
    Ninject.Extensions.
    centos6的安装
    ASP.NET 5+EntityFramework 7
    Nancy和MVC的简单对比
    ASP.NET 5应用是如何运行的(3)
    映射层超类型
    缓存模块
    怎样的中奖算法能让人信服(转)
    JQuery Easy Ui (Tree树)详解(转)
  • 原文地址:https://www.cnblogs.com/cobcmw/p/12367319.html
Copyright © 2011-2022 走看看