重粒子的运行轨迹

Compiling ...
baryon.cpp
baryon.cpp(1) : warning C0000: all glory is fleeing

导航

AngularJS实现文件异步上传

实现:前端AngularJs+后端servelt

依赖包:commons-fileupload.x.x.jar commons-io-x.x.jar

下载: http://commons.apache.org/proper/commons-fileupload/
http://commons.apache.org/proper/commons-io/ 文件上传前端利用AngularJs封好的http发起异步请求传递二进制文件。
代码:
第一步:

<div class="row " ng-show="up_doc">
            <div class="col-md-12 col-sm-12">
                <div class="z_up_common">
                    <div class="z_up_common_inner">
                        <div class="z_up_image">
                            <input id="file"
                                onchange="angular.element(this).scope().file_up_onclick(this)"
                                type="file"> </input>
                        </div>
                    </div>
                    <p class="up-tips">从我的电脑选择要上传的文档:按住CTRL可以上传多份文档</p>
                </div>
            </div>
        </div>


第二步:点击上传文档按钮确认选中文档开始上传

触发 file_up_onclick事件调用js方法
        $scope.file_up_onclick=function(){
        //1.获取文件对象
        var _file=document.getElementById("file");
        //2.实例化FormData对象
                   var $$fd=new FormData();
            //3.添加文件对象到FormData中
        $$fd.append("file",_file.files[0]);
            //4.开始异步上传
        $http({
            method:'post',
            data: $$fd,
            url:'//servlet/FileCommand',
            headers: {'Content-Type':undefined},
             /*序列化 formdata object*/
              transformRequest: angular.identity         
        }).success(function(data){    
        });
    };

第四步:servelt接收二进制文件
public class FileCommand extends HttpServlet{

    // 1.文件上传路径
    private static final String UPLOAD_DIRECTORY = "D:/文件上传";
    // 2.设置临时存储文件大小,当超过大小时,将先存储超出大小文件在临时目录
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 30; 
    // 3.设置最大文件上传值
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 2000; 
    // 4.最大请求值
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 2048; 

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

  doPost(request, response);
}

/**
 * @摘要 提供文件上传的方法
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    //1.设置字符编码为utf-8
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    // 2.检测是否为多媒体上传
    if (!ServletFileUpload.isMultipartContent(request)) {
        // 2.1如果不是则停止
        PrintWriter writer = response.getWriter();
        writer.println("Error: 表单必须包含 enctype=multipart/form-data");
        writer.flush();
        return  ;
    }
    // 3.配置上传参数
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //4. 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // 5.设置临时存储目录 java.io.tmpdir默认的临时文件路径为服务器的temp目录
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // 6.设置最大文件上传值
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // 7.设置最大请求值 (包含文件和表单数据)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    //8. 如果目录不存在则创建
    File uploadDir = new File(UPLOAD_DIRECTORY);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }
    try {
        // 10.解析请求的内容提取文件数据
        List<FileItem> formItems = upload.parseRequest(request);
        System.out.println("name="+request.getSession().getAttribute("name"));
            // 10.1迭代表单数据
        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()){
                    String nFileName = new File(item.getName()).getName();

                    String nPrefix=nFileName.substring(nFileName.lastIndexOf(".")+1);

                    nFileName=nFileName.substring(0,nFileName.lastIndexOf("."))    ;                

                    item.write(new File(UPLOAD_DIRECTORY+"/"+nFileName));

                    item.delete();

                    PrintWriter nWriter=response.getWriter();

                    nWriter.print("{\"prefix\":\""+nPrefix+"\",\"filename\":\""+nFileName+"\",\"filesize\":\""+item.getSize()+"\"}");
                }
                }
            }  
    } catch (Exception ex) {
        PrintWriter writer=response.getWriter();
        writer.print("error");
    }
}

第五步:查看文件是否在指定目录即可

posted on 2017-07-02 14:17  重粒子  阅读(161)  评论(0编辑  收藏  举报