Home Web Front-end JS Tutorial BootStrap fileinput.js file upload component example code

BootStrap fileinput.js file upload component example code

Feb 21, 2017 pm 02:40 PM

这篇文章主要介绍了BootStrap fileinput.js文件上传组件实例代码,非常不错,具有参考借鉴价值,需要的朋友可以参考下

1.首先我们下载好fileinput插件引入插件

<span style="font-size:14px;"><link type="text/css" rel="stylesheet" href="fileinput/css/fileinput.css" rel="external nofollow" /> 
<script type="text/javascript" src="fileinput/js/fileinput.js"></script> 
<script type="text/javascript" src="fileinput/js/fileinput_locale_zh.js"></script></span>
Copy after login

2.html设置:

<span style="font-size:14px;"><form enctype="multipart/form-data"> 
  <input id="file-file" class="file" type="file" multiple> 
</form></span>
Copy after login

3.初始化设置:

function initFileInput(ctrlName, uploadUrl) { 
      var control = $(&#39;#&#39; + ctrlName); 
      control.fileinput({ 
        resizeImage : true, 
        maxImageWidth : 200, 
        maxImageHeight : 200, 
        resizePreference : &#39;width&#39;, 
        language : &#39;zh&#39;, //设置语言 
        uploadUrl : uploadUrl, 
        uploadAsync : true, 
        allowedFileExtensions : [ &#39;jpg&#39;, &#39;png&#39;, &#39;gif&#39; ],//接收的文件后缀 
        showUpload : true, //是否显示上传按钮 
        showCaption : true,//是否显示标题 
        browseClass : "btn btn-primary", //按钮样式 
        previewFileIcon : "<i class=&#39;glyphicon glyphicon-king&#39;></i>", 
        maxFileCount : 3, 
        msgFilesTooMany : "选择图片超过了最大数量", 
        maxFileSize : 2000, 
      }); 
    }; 
   //初始化控件initFileInput(id,uploadurl)控件id,与上传路径 
    initFileInput("file-file", "/tqyh/pushMessAction");
Copy after login

注:要想使用控件自带的upload按钮,以及上传进度,必须用form包裹
(当然也可以在初始化的时加入 enctype: 'multipart/form-data',是一样的)但不用定义action

<strong><form enctype="multipart/form-data"> 
  <input id="file-file" class="file" type="file" multiple> 
</form></strong>
Copy after login

最后通过后台进行正常的上传就好了。

BootStrap fileinput.js文件上传组件实例代码

BootStrap fileinput.js文件上传组件实例代码


BootStrap fileinput.js文件上传组件实例代码

有些朋友说我没写明白,好吧我把后台代码贴出:

servlet:

@Override 
ublic void doPost(HttpServletRequest request,  
       HttpServletResponse response) 
       throws ServletException, java.io.IOException { 
    String path = request.getSession().getServletContext().getRealPath("/headUpload"); 
  UploadMediaService upload=new UploadMediaService(); 
  String headimage=upload.getMeiaName(path, request); 
  request.getSession().setAttribute("headname",headimage ); 
  System.out.println("文件上传成功"); 
 } 
 @Override 
ublic void doGet(HttpServletRequest request,  
           HttpServletResponse response) 
    throws ServletException, java.io.IOException { 
  doPost( request, response); 
 }
Copy after login

其实后台不用可以接收,我们通过解析request就能获取一个或者多个上传的文件。上面代码主要核心代码:

<span style="font-size:14px;">String path = request.getSession().getServletContext().getRealPath("/headUpload"); 
      UploadMediaService upload=new UploadMediaService(); 
      String headimage=upload.getMeiaName(path, request);</span>
Copy after login

<span style="font-size:14px;">UploadMediaService : 
/** 
   * 上传媒体文件,存储在服务端 
   * 
   * @param path 获取文件需要上传到的路径  
   * @param request 客户端请求 
   * @return 
   */ 
  public static String uploadLocalMedia(String path,HttpServletRequest request){ 
    String filename ="";  
     //获得磁盘文件条目工厂  
    DiskFileItemFactory factory = new DiskFileItemFactory();  
    //如果没以下两行设置的话,上传大的 文件 会占用 很多内存,  
    //设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同  
    /** 
     * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,  
     * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的  
     * 然后再将其真正写到 对应目录的硬盘上 
     */  
    factory.setRepository(new File(path));  
    //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室  
    factory.setSizeThreshold(1024*1024) ;  
    //高水平的API文件上传处理  
    ServletFileUpload upload = new ServletFileUpload(factory);  
    try {  
      //可以上传多个文件  
      List<FileItem> list = upload.parseRequest(request);  
      for(FileItem item : list) {  
        //如果获取的 表单信息是普通的 文本 信息  
        if(item.isFormField()) {            
          //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的  
          String value = item.getString() ;  
        } else{  
          //对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,视频这些  
          /** 
           * 以下三步,主要获取 上传文件的名字 
           */  
          //获取路径名  
          String value = item.getName() ;  
          //索引到最后一个反斜杠  
          int start = value.lastIndexOf("\\");  
          //截取 上传文件的 字符串名字,加1是 去掉反斜杠,  
          filename = value.substring(start+1);  
          System.out.println("filename="+ filename); 
          //真正写到磁盘上  
          //它抛出的异常 用exception 捕捉  
          //item.write( new File(path,filename) );//第三方提供的  
          //手动写的  
          OutputStream out = new FileOutputStream(new File(path,filename));  
          InputStream in = item.getInputStream() ;  
          int length = 0 ;  
          byte [] buf = new byte[1024] ;  
          // in.read(buf) 每次读到的数据存放在  buf 数组中  
          while( (length = in.read(buf) ) != -1) {  
            //在  buf 数组中 取出数据 写到 (输出流)磁盘上  
            out.write(buf, 0, length);   
          }  
          in.close();  
          out.close();  
        }  
      }  
    } catch (FileUploadException e) {  
      log.error("文件上传异常:",e); 
    } catch (Exception e) {  
      log.error("文件处理IO异常:",e); 
    }  
    return filename ; 
  } 
</span>
Copy after login

以上所述是小编给大家介绍的BootStrap fileinput.js文件上传组件实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家PHP中文网的支持!

更多BootStrap fileinput.js文件上传组件实例代码相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles