搜索词>>ie9文件上传 耗时0.0140
  • IE9 jQuery ajax文件上传兼容问题解决

    IE9 jQuery ajax文件上传兼容问题解决。主要通过jQuery的jquery.form插件解决的IE9不支持formData的文件上传问题。<h2>1.准备</h2> 下载jQuery1.x版本(测试用v1.12.4)<br /> 下载jQuery的form插件(<a href="http://plugins.jquery.com/form/" rel="external nofollow" target="_blank">下载地址</a>)<br /> 本例子是通过Java后端进行测试的,后端为spring boot框架 <h2>2.后端代码</h2> 1测试的controller代码 <pre> <code class="language-java">package com.example; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class TestController { @GetMapping(value = { "/", "/index.html" }) public Object index() { return new ModelAndView("index"); } @PostMapping(value = { "/fileupload.do" }, produces = { "text/html;charset=UTF-8" }) @ResponseBody public Object fileUpload(String name, MultipartFile file) { try { if (file.getBytes().length > 0) { return "{\"message\":\"success\",\"name\":\"" + name + "\"}"; } else { return "{\"message\":\"fail\"}"; } } catch (Exception e) { throw new RuntimeException("文件上传异常"); } } @PostMapping(value = { "/fileupload2.do" }/*, produces = { "text/html;charset=UTF-8" }*/) public void fileUpload2(String name, MultipartFile file,HttpServletResponse response) { try { if (file.getBytes().length > 0) { response.setContentType(""); response.setHeader("Content-Type", "text/html;charset=UTF-8"); response.getWriter().write("{\"message\":\"success\",\"name\":\"" + name + "\"}"); } else { response.setHeader("Content-Type", "text/html;charset=UTF-8"); response.getWriter().write("{\"message\":\"fail\"}"); } } catch (Exception e) { throw new RuntimeException("文件上传异常"); } } } </code></pre> <span style="color:#e74c3c">注意:上面的第一种写法<strong>produces = { "text/html;charset=UTF-8" }</strong>必须这样写,其他写法则会出现各种问题</span> <p> </p> <h2>3.后端代码</h2> 1HTML页面代码 <pre> <code class="language-html"><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>测试</title> </head> <body> <form method="post" enctype="multipart/form-data" id="upload-form"> <input type="text" name="name" /> <input type="file" name="file"/> </form> <button type="button" id="btn-upload">上传测试</button> <script type="text/javascript" src="/libs/jquery.min.js"></script> <script type="text/javascript" src="/libs/jquery.form.js"></script> <script type="text/javascript" src="/libs/index.js"></script> </body> </html></code></pre> <br /> 2.index.js文件代码 <pre> <code class="language-javascript">/** * */ $(function() { $('#btn-upload').click(function(){ var options = { url : "/fileupload.do", success : function(data) { var returnData = JSON.parse(data); alert(data); }, resetForm : true, }; $("#upload-form").ajaxSubmit(options); }) })</code></pre> <h2>4jQuery form控件API</h2> <h2>Options</h2> <p><strong>Note:</strong> All standard <a href="http://api.jquery.com/jQuery.ajax" rel="external nofollow" target="_blank">$.ajax</a> options can be used.</p> <h3>beforeSerialize</h3> <p>Callback function invoked prior to form serialization. Provides an opportunity to manipulate the form before its values are retrieved. Returning <code>false</code> from the callback will prevent the form from being submitted. The callback is invoked with two arguments: the jQuery wrapped form object and the options object.</p> <pre> <code class="language-javascript">beforeSerialize: function($form, options) { // return false to cancel submit }</code></pre> <h3>beforeSubmit</h3> <p>Callback function invoked prior to form submission. Returning <code>false</code> from the callback will prevent the form from being submitted. The callback is invoked with three arguments: the form data in array format, the jQuery wrapped form object, and the options object.</p> <pre> <code class="language-javascript">beforeSubmit: function(arr, $form, options) { // form data array is an array of objects with name and value properties // [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] // return false to cancel submit }</code></pre> <h3>filtering</h3> <p>Callback function invoked before processing fields. This provides a way to filter elements.</p> <pre> <code class="language-javascript">filtering: function(el, index) { if ( !$(el).hasClass('ignore') ) { return el; } }</code></pre> <h3>clearForm</h3> <p>Boolean flag indicating whether the form should be cleared if the submit is successful</p> <h3>data</h3> <p>An object containing extra data that should be submitted along with the form.</p> <pre> <code>data: { key1: 'value1', key2: 'value2' } </code></pre> <h3>dataType</h3> <p>Expected data type of the response. One of: null, 'xml', 'script', or 'json'. The dataType option provides a means for specifying how the server response should be handled. This maps directly to jQuery's dataType method. The following values are supported:</p> <ul> <li>'xml': server response is treated as XML and the 'success' callback method, if specified, will be passed the responseXML value</li> <li>'json': server response will be evaluted and passed to the 'success' callback, if specified</li> <li>'script': server response is evaluated in the global context</li> </ul> <h3>delegation</h3> <p>true to enable support for event delegation <em>requires jQuery v1.7+</em></p> <pre> <code class="language-javascript">// prepare all existing and future forms for ajax submission $('form').ajaxForm({ delegation: true });</code></pre> <h3>error</h3> <p>Callback function to be invoked upon error.</p> <h3>forceSync</h3> <p>Only applicable when explicity using the iframe option or when uploading files on browses that don't support XHR2. Set to <code>true</code> to remove the short delay before posting form when uploading files. The delay is used to allow the browser to render DOM updates prior to performing a native form submit. This improves usability when displaying notifications to the user, such as "Please Wait..."</p> <h3>iframe</h3> <p>Boolean flag indicating whether the form should <em>always</em> target the server response to an iframe instead of leveraging XHR when possible.</p> <h3>iframeSrc</h3> <p>String value that should be used for the iframe's src attribute when an iframe is used.</p> <h3>iframeTarget</h3> <p>Identifies the iframe element to be used as the response target for file uploads. By default, the plugin will create a temporary iframe element to capture the response when uploading files. This options allows you to use an existing iframe if you wish. When using this option the plugin will make no attempt at handling the response from the server.</p> <h3>method</h3> <p>The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT').</p> <h3>replaceTarget</h3> <p>Optionally used along with the the target option. Set to true if the target should be replaced or false if only the target contents should be replaced.</p> <h3>resetForm</h3> <p>Boolean flag indicating whether the form should be reset if the submit is successful</p> <h3>semantic</h3> <p>Boolean flag indicating whether data must be submitted in strict semantic order (slower). Note that the normal form serialization is done in semantic order with the exception of input elements of <code>type="image"</code>. You should only set the semantic option to true if your server has strict semantic requirements and your form contains an input element of <code>type="image"</code>.</p> <h3>success</h3> <p>Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following standard jQuery arguments:</p> <ol> <li><code>data</code>, formatted according to the dataType parameter or the dataFilter callback function, if specified</li> <li><code>textStatus</code>, string</li> <li><code>jqXHR</code>, object</li> <li><code>$form</code> jQuery object containing form element</li> </ol> <h3>target</h3> <p>Identifies the element(s) in the page to be updated with the server response. This value may be specified as a jQuery selection string, a jQuery object, or a DOM element.</p> <h3>type</h3> <p>The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT').<br /> An alias for <code>method</code> option. Overridden by the <code>method</code> value if both are present.</p> <h3>uploadProgress</h3> <p>Callback function to be invoked with upload progress information (if supported by the browser). The callback is passed the following arguments:</p> <ol> <li>event; the browser event</li> <li>position (integer)</li> <li>total (integer)</li> <li>percentComplete (integer)</li> </ol> <h3>url</h3> <p>URL to which the form data will be submitted.</p> <hr /> <h2>Utility Methods</h2> <h3>formSerialize</h3> <p>Serializes the form into a query string. This method will return a string in the format: <code>name1=value1&name2=value2</code></p> <pre> <code>var queryString = $('#myFormId').formSerialize();</code></pre> <h3>fieldSerialize</h3> <p>Serializes field elements into a query string. This is handy when you need to serialize only part of a form. This method will return a string in the format: <code>name1=value1&name2=value2</code></p> <pre> <code>var queryString = $('#myFormId .specialFields').fieldSerialize();</code></pre> <h3>fieldValue</h3> <p>Returns the value(s) of the element(s) in the matched set in an array. This method always returns an array. If no valid value can be determined the array will be empty, otherwise it will contain one or more values.</p> <h3>resetForm</h3> <p>Resets the form to its original state by invoking the form element's native DOM method.</p> <h3>clearForm</h3> <p>Clears the form elements. This method emptys all of the text inputs, password inputs and textarea elements, clears the selection in any select elements, and unchecks all radio and checkbox inputs. It does <em>not</em> clear hidden field values.</p> <h3>clearFields</h3> <p>Clears selected field elements. This is handy when you need to clear only a part of the form.</p> <hr /> <h2>File Uploads</h2> <p>The Form Plugin supports use of XMLHttpRequest Level 2 and <a href="https://developer.mozilla.org/en/XMLHttpRequest/FormData" rel="external nofollow" target="_blank">FormData</a> objects on browsers that support these features. As of today (March 2012) that includes Chrome, Safari, and Firefox. On these browsers (and future Opera and IE10) files uploads will occur seamlessly through the XHR object and progress updates are available as the upload proceeds. For older browsers, a fallback technology is used which involves iframes. <a href="http://malsup.com/jquery/form/#file-upload" rel="external nofollow" target="_blank">More Info</a></p>
  • ie9 jquery ajax跨域问题解决

    ie9 jquery ajax跨域问题解决, ajax ie9 跨域问题解决,jquery,ajax,ie9<strong><img alt="IE9" class="img-thumbnail" src="/assist/images/blog/a177036b22b4400e9adf48b25e574615.png" /><br /> 描述</strong><br /> ie9 jquery ajax跨域问题<br /> <br /> <strong>解决步骤</strong> <h2>一.导入相关文件</h2> 导入需要的jquery依赖文件,这里用的jquery的1.x版本 <pre> <code class="language-javascript"><!-- jQuery引入 --> <script type="text/javascript" src="../libs/jQuery/jquery.js"></script></code></pre> <h2>二.设置IE浏览器支持跨域访问</h2> <strong>2.1打开IE浏览器,选择设置里面的intelnet选项,如下图:</strong><br /> <img alt="IE浏览器 intelnet选项" class="img-thumbnail" src="/assist/images/blog/4e7c330e6ffc49b2bb181f700d641ad4.png" /><br /> <strong>2.2选择intelnet选项面板中的安全模块,并点击自定义级别,如下图</strong><br /> <img alt="intelnet选项面板中的安全模块" class="img-thumbnail" src="/assist/images/blog/4d397e7dfd1e480c9aacb4c44b912f27.png" /><br /> <strong>2.3找到通过遇访问数据源,选择启用,如图:<br /> <img alt="找到通过遇访问数据源,选择启用" class="img-thumbnail" src="/assist/images/blog/c100d8f866764a918a195f2f44690848.png" /></strong> <h2>三.编写一个jquery的ajax请求demo</h2> <pre> <code class="language-html"><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jquery IE9 跨域问题解决</title> </head> <body> <!-- jQuery引入 --> <script type="text/javascript" src="../libs/jQuery/jquery.js"></script> <script type="text/javascript"> $(function() { $.ajax({ url:'http://localhost:8080/test.do', type:'GET', crossDomain: true == !(document.all), processData: false, success:function(data){ alert(data); }, error: function(jqXHR,err) { alert(jqXHR.status+": "+jqXHR.statusText); } }); }) </script> </body> </html></code></pre> <br /> 运行:<br /> <img alt="运行结果" class="img-thumbnail" src="/assist/images/blog/aaa3f74ed2d6478aa6a8633c6c52b3b6.png" /><br /> <br /> 服务代码:这里是java提供的测试访问: <pre> <code class="language-java"> @GetMapping("test.do") @ResponseBody public String test(HttpServletResponse response){ response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Origin", "*"); return "Hello Form Server"; }</code></pre> <br />  
  • MIME 参考手册/HTTP文件上传格式过滤

    MIME 参考手册/HTTP文件上传格式过滤MIME 参考手册/HTTP文件上传格式过滤​​​​​​​
  • HTML5+ajax上传图片/文件以及FormData使用简单讲解

    HTML5+ajax上传图片/文件以及FormData使用简单讲解,HTML5,ajax上传文件,ajaxHTML5+ajax上传图片/文件以及FormData使用简单讲解<br /> <br /> HTML5中FormData的使用,解决ajax上传文件/图片难题<br /> <strong>1.FormData的创建和使用方式一</strong><br /> 创建一个空的 FormData <pre> <code class="language-javascript">var fd= new FormData();</code></pre> <br /> 使用 append() 方法向该对象里添加字段 <pre> <code class="language-javascript">fd.append("username", "Groucho"); fd.append("userfile", fileInputElement.files[0]);</code></pre> <br /> <strong>2.FormData的创建和使用方式二</strong><br /> 使用HTML表单来初始化一个FormData对象 <pre> <code class="language-html"><form id="test-form"> <input type="text" name="name"/> <input type="password" name="pwd"/> </form></code></pre>   <pre> <code class="language-javascript">var formElement = document.getElementById("test-form"); var newFormData = new FormData(formElement);</code></pre> <br /> 在有了FormData对象之后使用ajax(这里简单引用的jQuery的ajax)<br />   <pre> <code class="language-javascript">$.ajax({     url:'Your Post Url',     type:'POST',//上传文件必须为POST,查看解释一     data:newFormData,//FormData对象     processData:false,//不转换请求数据     contentType:false,//contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符     success:function(data){         //成功回调     },     error:function(ex){         //错误回调     } });</code></pre> <br /> <em>解释一:这里我们就要先说说在 http 中传输文件的问题。起初,http 协议中没有上传文件方面的功能,直到 rfc1867 为 http 协议添加了这个功能。当然在 rfc1867 中限定 form 的 method 必须为 POST , enctype = “multipart/form-data” 以及<input type = "file">.</em>
  • Spring mvc文件下载IE/Edge中文乱码解决

    Spring mvc文件下载IE/Edge中文乱码解决,在spring mvc项目开发中,我们可能经常遇到文件的上传和下载操作。这里将讲解在IE/Edge浏览器中文件下载中文乱码的解决方法。<h2>引言</h2>     在spring mvc项目开发中,我们可能经常遇到文件的上传和下载操作。这里将讲解在IE/Edge浏览器中文件下载中文乱码的解决方法。 <h2>一.解决spring mvc IE/Edge浏览器乱码</h2> 编写controller测试代码: <pre> <code class="language-java">package net.xqlee.project.controller; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class FileController { /** * 文件下载 * * @param request * @param response */ @GetMapping("download.do") public void downloadFile(HttpServletRequest request, HttpServletResponse response) { try { String fileName = "中文测试.DAT"; response.getWriter().write("中文测试你好"); fileName = dealFileName(request, fileName); response.addHeader("Content-Disposition", "attachment;filename=" + fileName); } catch (Exception e) { e.printStackTrace();// logger } } /** * 处理IE/Edge(win10)浏览器中文乱码 * * @param request * @param fileName * @return */ public String dealFileName(HttpServletRequest request, String fileName) { try { String codeFileName = ""; String agent = request.getHeader("User-Agent"); if (agent == null) { return fileName; } agent = agent.toUpperCase(); if (null == agent) { codeFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); } else if (-1 != agent.indexOf("MSIE") || -1 != agent.indexOf("TRIDENT") || -1 != agent.indexOf("EDGE")) { codeFileName = URLEncoder.encode(fileName, "UTF-8"); } else { codeFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); } return codeFileName; } catch (Exception e) { e.printStackTrace();// logger return fileName; } } } </code></pre> <br /> 注意观察上面的代码,解决乱码主要在dealFilename();这个方法中进行处理的。FileName进行get UTF8字符集是因为当前代码的编码格式为UTF-8如果是GBK则更改为GBK<br /> <br /> 二.测试IE/Edge浏览器中文乱码的解决 <h3>2.1启动刚才controller所在的项目。</h3> <h3>2.2访问文件下载地址查看结果</h3> 文件下载地址为:http://localhost:8080/download.do<br /> <br /> 观察IE浏览器:<br /> <img alt="Spring MVC IE浏览器乱码解决测试结果" class="img-thumbnail" src="/assist/images/blog/57cdaf3f0eca43ba8934d277eda4e82a.png" /><br /> <br /> 从上图可以看到中文已经正常显示。接下来测试win10的Edge浏览器:<br /> <img alt="Spring MVC Edge浏览器乱码解决测试结果" class="img-thumbnail" src="/assist/images/blog/6c691febe79746d3a742b487b00efb84.png" />从上图也能看到中午呢乱码问题已经得到解决。<br />  
  • el-upload图片上传安卓无法调用相机问题解决

    el-upload图片上传安卓无法调用相机问题解决,vue 使用element-ui的文件上传组件el-upload安卓无法调用相机问题解决办法问题描述vue 使用element-ui的文件上传组件el-upload安卓无法调用相机,默认调用的文件系统。解决办法
  • linux系统中ftp 上传和下载文件shell脚本编写

    linux系统中ftp 上传和下载文件shell脚本编写1.ftp单文件下载 <pre> <code class="language-bash">#!/bin/bash FTILE_NAME=$1 ftp -n <<- EOF #需要下载文件的主机或者IP地址 open www.leftso.com #配置用户名和密码 user username password #切换远程端目录 cd /home/xqlee/backup #切换本地存放目录 lcd /home/tomcat/test/ftp #二进制方式传输 bin #执行下载文件操作 prompt get $FTILE_NAME #退出 bye EOF</code></pre> <br /> 上面脚本执行方式: <pre> <code>./ftp-shellscriptname.sh 文件名</code></pre> <strong><span style="color:#9b59b6">注意:脚本需要修改权限使其拥有执行权限如chmod 755 脚本名称</span></strong><br /> <br /> 2.下载多个文件 <pre> <code>#!/bin/bash ftp -n <<- EOF #需要下载文件的主机或者IP地址 open www.leftso.com #配置用户名和密码 user username password #切换远程端目录 cd /home/xqlee/backup #切换本地存放目录 lcd /home/tomcat/test/ftp #二进制方式传输 bin #执行下载文件操作 prompt mget 文件名1 文件名2 *.xml ... #退出 bye EOF</code></pre> <br /> <strong><span style="color:#1abc9c">下载多个文件使用过得命令是mget,mget后面跟着文件名称规则多个规则之间使用空格隔开</span></strong><br /> 3.ftp上传文件 <pre> <code class="language-bash">#!/bin/bash FTILE_NAME=$1 ftp -n <<- EOF #需要上载文件的主机或者IP地址 open www.leftso.com #配置用户名和密码 user username password #切换远程端目录 cd /home/xqlee/backup #切换本地存放目录 lcd /home/tomcat/test/ftp #二进制方式传输 bin #执行上载文件操作 prompt put $FTILE_NAME #退出 bye EOF</code></pre> <br /> 不难观察出,上传和下载只是一个命令的区别,put与get<br /> <br /> 4.ftp上传多个文件 <pre> <code class="language-bash">#!/bin/bash FTILE_NAME=$1 ftp -n <<- EOF #需要上载文件的主机或者IP地址 open www.leftso.com #配置用户名和密码 user username password #切换远程端目录 cd /home/xqlee/backup #切换本地存放目录 lcd /home/tomcat/test/ftp #二进制方式传输 bin #执行上载文件操作 prompt mput 文件名规则1 文件名2 ... #退出 bye EOF</code></pre> <br /> 本ftp脚本原理都是通过实际测试出来的结果,在我使用这个命令前我百度搜索一圈居然很多错误比如get后面跟着多个名称就是下载多个文件,实际是只下载最后一个文件名的文件..<br /> 本文档仅做个人使用参考,欢迎提出建议<br /> <br /> <br />  
  • spring boot 文件上传 REST风格API ajax方式-Java编程

    Java编程之Spring Boot 文件上传 REST风格API ajax方式<h2>一、摘要说明</h2>   这篇文章将告诉你在spring boot(REST 风格)WEB项目中如何用ajax请求上传文件。<br /> <br />   本文章中需要使用的工具: <ol> <li>Spring Boot 1.4.3.RELEASE</li> <li>Spring 4.3.5.RELEASE</li> <li>Thymeleaf</li> <li>jQuery (webjars)</li> <li>Maven</li> <li>Embedded Tomcat 8.5.6</li> <li>Google Chrome 浏览器(Network Inspect)</li> </ol> <h2>二、项目结构</h2> 一个标准的maven项目结构<br /> <img alt="项目结构" class="img-thumbnail" src="/assist/images/blog/811600c9be364e56b3c68ebbe78e0b07.png" /> <h2>三、项目依赖</h2> 声明一个外部的jQuery webjar依赖项,用于HTML表单中的Ajax请求。<br /> <br /> <strong>pom.xml</strong> <pre> <code class="language-xml"><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mkyong</groupId> <artifactId>spring-boot-file-upload</artifactId> <packaging>jar</packaging> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- hot swapping, disable cache for template, enable live reload --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.2.4</version> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project></code></pre> <h2>四、文件上传</h2> 为了支持AJAX请求和响应, 最简单的方式是返回<code>ResponseEntity</code>. <h2>4.1下面的例子演示了上传文件的三种可能方式:</h2> <ol> <li>单个文件上传 – <code>MultipartFile</code></li> <li>多个文件上传– <code>MultipartFile[]</code></li> <li>Map file upload to a Model – <code>@ModelAttribute</code></li> </ol> <strong>RestUploadController.java</strong> <pre> <code class="language-java">import com.mkyong.model.UploadModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @RestController public class RestUploadController { private final Logger logger = LoggerFactory.getLogger(RestUploadController.class); //Save the uploaded file to this folder private static String UPLOADED_FOLDER = "F://temp//"; // 3.1.1 Single file upload @PostMapping("/api/upload") // If not @RestController, uncomment this //@ResponseBody public ResponseEntity<?> uploadFile( @RequestParam("file") MultipartFile uploadfile) { logger.debug("Single file upload!"); if (uploadfile.isEmpty()) { return new ResponseEntity("please select a file!", HttpStatus.OK); } try { saveUploadedFiles(Arrays.asList(uploadfile)); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK); } // 3.1.2 Multiple file upload @PostMapping("/api/upload/multi") public ResponseEntity<?> uploadFileMulti( @RequestParam("extraField") String extraField, @RequestParam("files") MultipartFile[] uploadfiles) { logger.debug("Multiple file upload!"); // Get file name String uploadedFileName = Arrays.stream(uploadfiles).map(x -> x.getOriginalFilename()) .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" , ")); if (StringUtils.isEmpty(uploadedFileName)) { return new ResponseEntity("please select a file!", HttpStatus.OK); } try { saveUploadedFiles(Arrays.asList(uploadfiles)); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded - " + uploadedFileName, HttpStatus.OK); } // 3.1.3 maps html form to a Model @PostMapping("/api/upload/multi/model") public ResponseEntity<?> multiUploadFileModel(@ModelAttribute UploadModel model) { logger.debug("Multiple file upload! With UploadModel"); try { saveUploadedFiles(Arrays.asList(model.getFiles())); } catch (IOException e) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } return new ResponseEntity("Successfully uploaded!", HttpStatus.OK); } //save file private void saveUploadedFiles(List<MultipartFile> files) throws IOException { for (MultipartFile file : files) { if (file.isEmpty()) { continue; //next pls } byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); } } }</code></pre> <h2>4.2选择4.1中的第三种方式上传文件并且使用注解@ModelAttribute</h2> <strong>UploadModel.java</strong> <pre> <code class="language-java">import org.springframework.web.multipart.MultipartFile; public class UploadModel { private String extraField; private MultipartFile[] files; //getters and setters }</code></pre> <h2>五、视图文件的编写</h2> HTML form for multiple file uploads.<br /> <strong>upload.html</strong> <pre> <code class="language-html"><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <h1>Spring Boot - Multiple file upload example - AJAX</h1> <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> <input type="text" name="extraField"/><br/><br/> <input type="file" name="files"/><br/><br/> <input type="file" name="files"/><br/><br/> <input type="submit" value="Submit" id="btnSubmit"/> </form> <h1>Ajax Post Result</h1> <pre> <span id="result"></span> </pre> <script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script> <script type="text/javascript" src="js/main.js"></script> </body> </html></code></pre> <h2>六、jQuery – Ajax Request</h2> jQuery通过f<code>#id获取form</code>,并且发送multipart form 数据通过ajax请求.<br /> <strong>resources/static/js/main.js</strong> <pre> <code class="language-javascript">$(document).ready(function () { $("#btnSubmit").click(function (event) { //stop submit the form, we will post it manually. event.preventDefault(); fire_ajax_submit(); }); }); function fire_ajax_submit() { // Get form var form = $('#fileUploadForm')[0]; var data = new FormData(form); data.append("CustomField", "This is some extra data, testing"); $("#btnSubmit").prop("disabled", true); $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "/api/upload/multi", data: data, //http://api.jquery.com/jQuery.ajax/ //https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects processData: false, //prevent jQuery from automatically transforming the data into a query string contentType: false, cache: false, timeout: 600000, success: function (data) { $("#result").text(data); console.log("SUCCESS : ", data); $("#btnSubmit").prop("disabled", false); }, error: function (e) { $("#result").text(e.responseText); console.log("ERROR : ", e); $("#btnSubmit").prop("disabled", false); } }); }</code></pre> <h2>七、Exception Handler异常拦截</h2> 拦截来自 Ajax请求的异常, 只需要继承 <code>ResponseEntityExceptionHandler</code> 并且返回 <code>ResponseEntity</code>.<br /> <strong>RestGlobalExceptionHandler.java</strong> <pre> <code class="language-java">import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest; //http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling @ControllerAdvice public class RestGlobalExceptionHandler extends ResponseEntityExceptionHandler { // Catch file size exceeded exception! @ExceptionHandler(MultipartException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); return new ResponseEntity(ex.getMessage(), status); // example //return new ResponseEntity("success", responseHeaders, HttpStatus.OK); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }</code></pre> <h2>八、演示</h2> 使用默认的嵌入式Tomcat启动Spring启动<code>mvn spring-boot:run</code>.<br /> 8.1访问http://localhost:8080/,选择几个文件并单击submit以触发ajax请求。<br /> <img alt="访问并上传" class="img-thumbnail" src="/assist/images/blog/19d6d8c691d04a079fd5a18adc7560fa.png" /><br /> 8.2 Google Chrome浏览器,检查“网络检查”中的请求和响应<br /> <img alt="观察请求" class="img-thumbnail" src="/assist/images/blog/ae51363c32cf415b943dbdc57d659470.png" /><br /> 8.4 Google Chrome, “Request Payload”<br /> <img alt="上传内容" class="img-thumbnail" src="/assist/images/blog/7f1ff5d5dde64d89ae7afd664c5df0f5.png" /> <h2>9.curl工具测试</h2> More testing with <code>cURL</code> command.<br /> 9.1测试单个文件上传 <pre> <code>$ curl -F file=@"f:\\data.txt" http://localhost:8080/api/upload/ Successfully uploaded - data.txt</code></pre> <br /> 9.2.测试多个文件上传 <pre> <code>$ curl -F extraField="abc" -F files=@"f://data.txt" -F files=@"f://data2.txt" http://localhost:8080/api/upload/multi/ Successfully uploaded - data.txt , data2.txt</code></pre> 9.3测试多个文件上传使用maps to Model模式 <pre> <code>$ curl -F extraField="abc" -F files=@"f://data.txt" -F files=@"f://data2.txt" http://localhost:8080/api/upload/multi/model Successfully uploaded! </code></pre> <br /> 9.4测试一个大文件(超过100MB),将会提示下面的错误信息 <pre> <code>$ curl -F file=@"F://movies//300//Sample.mkv" http://localhost:8080/api/upload/ Attachment size exceeds the allowable limit! (10MB)</code></pre> <h2>十、curl测试加自定义错误对象测试</h2> 10.1创建一个自定义对象去存放异常信息<br /> <strong>CustomError.java</strong> <pre> <code class="language-java">public class CustomError { String errCode; String errDesc; public CustomError(String errCode, String errDesc) { this.errCode = errCode; this.errDesc = errDesc; } //getters and setters }</code></pre> 10.2更新全局的异常拦截支持自定义异常信息<br /> <strong>RestGlobalExceptionHandler.java</strong> <pre> <code class="language-java">import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest; @ControllerAdvice public class RestGlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(MultipartException.class) @ResponseBody ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) { HttpStatus status = getStatus(request); return new ResponseEntity(new CustomError("0x000123", "Attachment size exceeds the allowable limit! (10MB)"), status); //return new ResponseEntity("Attachment size exceeds the allowable limit! (10MB)", status); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } }</code></pre> <br /> 10.3再次上传一个大文件 <pre> <code>$ curl -F file=@"F://movies//300//Sample.mkv" http://localhost:8080/api/upload/ {"errCode":"0x000123","errDesc":"Attachment size exceeds the allowable limit! (10MB)"}</code></pre> <br /> <a href="http://www.mkyong.com/wp-content/uploads/2017/01/spring-boot-file-upload-ajax-rest.zip" rel="external nofollow" target="_blank">demo项目下载</a>
  • windows7/win7如何把IE9/IE11恢复到IE8

    前言在写这篇文章前,我百度了很多教程,大多数都是相似的,结果都是失败前言在写这篇文章前,我百度了很多教程,大多数都是相似的,结果都是失败。失败的结果导致IE卸载了装不上。尴尬的只有重装系统。​本文主要是针对互联网上千篇一律的错误win7 IE9/IE11恢复到IE8进行纠正并记录详细操作步骤。​​​​​​​​win7 恢复IE8步骤1:首先关闭IE x(x代表IE 版本IE9/IE10/IE11)​点击计算机属性,得到下面:​点击控制面板得到下面:​点击上方的卸载程序得到下面界面:​点击打开或关闭Windows功能,得到下面界面​将上图中的internet Explorer 9前面的复选框 钩 去掉,再点击确定​关闭IE 浏览器​到此步骤一完毕。步骤二:卸载IE9(IE高版本)首先我们到程序卸载的界面​点击查看已安装的更新,得到下面界面:​重上方界面中找到IE9(高版本IE),并卸载,这里有语言包和IE程序,优先卸载语言包,再卸载程序​卸载后需要重启,点击立即重启即可。至此,步骤二卸载完成;步骤三:启用IE8步骤二重启系统后,我们先进入程序卸载界面​我看可以看到下面的​上图中点Internet Explorer8 前面的复选框,然后点击确定进行启用IE8​提示重启,重启即可这时候开机我们将得到一个IE8​​​
  • CKEditor4.4整合SprngMVC实现上传图片

    CKEditor4.4整合SprngMVC实现上传图片本教程适合java任何框架[springMVC,Struts1-2]以及servlet,其他语言同样可以参照传递参数方式<br /> 前言:ckeditorPHP版本是有个ckfinder插件管理图片库的,可是java版本却还是灰色的。<br /> 本人使用的是ckeditor最新版本4.4.7<br /> CKEditor的编辑器工具栏中有一项“图片域”,该工具可以贴上图片地址来在文本编辑器中加入图片,但是默认没有图片上传。<br /> <br /> 一、去掉预览中的英语<br /> 预览中是用英语说明的,对于我们国人来说是没有意义的。我们需要把它改成我们国语或者清空。那么问题来了?我们该怎么改呢?<br /> 方法有两种:<br /> <img alt="去掉预览中的英语" class="img-thumbnail" src="/assist/images/blog/7253e9f7-d1b8-4f69-b8ba-d7d8b62fe93b.png" style="height:543px; width:494px" /><br /> 1.修改image插件的源文件,打开ckeditor/plugins/image/dialogs/image.js,搜索“b.config.image_previewText”就能找到这段英语了,(b.config.image_previewText||'')单引号中的内容全删了<br />    <br /> 2.修改config.js配置文件,打开ckeditor/config.js, 在CKEDITOR.editorConfig = function(config) {….}中添加 <pre> <code class="language-apache">config.image_previewText = '外联图片请直接输入图片地址。';//这里的内容自己可以定义。同样可以设置""空</code></pre> 二、打开ckeditor默认的图片上传控件<br /> Ckeditor实际是有一个默认的图片上传控件的,首先打开ckeditor/config.js配置文件在CKEDITOR.editorConfig = function(config) {….}中添加 <pre> <code class="language-javascript">config.filebrowserImageUploadUrl = 'upload.do?type=Image';//提示这里的type=image表示开启的图片上传功能。Flash,file上传的默认控件打开配置方式相同只是type不同 /* * config.filebrowserUploadUrl = 'upload.do?type=File'; * config.filebrowserImageUploadUrl = 'upload.do?type=Image'; * config.filebrowserFlashUploadUrl = 'upload.do?type=Flash'; */ </code></pre> 配置好了配置文件,这时候我们打开编辑器的图片插入界面:<br /> <img alt="对应前面的图片我们不难看出现在已经有上传图片的控件了。" class="img-thumbnail" src="/assist/images/blog/3fdf6fe3-119e-4fed-9ec9-dd252cef9608.png" style="height:487px; width:468px" /><br /> 对应前面的图片我们不难看出现在已经有上传图片的控件了。<br /> 三、结合后台上传图片<br /> 根据ckeditor的官方api我们知道,配置上传图片的form表单的action需要在配置文件ckeditor/config.js中添加 <pre> <code>config.filebrowserImageUploadUrl = 'upload.do?type=Image';//upload.do上传文件的请求url</code></pre> 这里的upload.do即上传的action这里对于java的Struts框架还是springMVC框架都是公用的。配置好了这里我们继续回到界面;<br /> 既然我们要上传图片到后端,我们首先得知道上传控件给我们定义的属性名分别是什么,那么我们打开火狐浏览器的firbug,随意点击一张图片点击上传:<br /> <img alt="这里我们可以看到通过get到后台的参数有" class="img-thumbnail" src="/assist/images/blog/dc3923a7-e322-4ddb-8904-06faa8cd1888.png" style="height:139px; width:393px" /><br /> 这里我们可以看到通过get到后台的参数有<br /> CKEditor值:editor<br /> CKEditorFuncNum值:0<br /> langCode值:zh-cn<br /> type值:Image<br /> <img alt="这里我们又可以知道通过post我们传到后端的参数" class="img-thumbnail" src="/assist/images/blog/43fee6c5-4e7d-4b9c-81b9-21bca48a37e3.png" style="height:161px; width:495px" /><br /> 这里我们又可以知道通过post我们传到后端的参数<br /> Upload值:二进制的图片<br /> 既然我们知道了这些参数,那么我们在后端就知道怎么接受参数了。<br /> SpringMVC接收参数方法: <pre> <code>import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; /** * * * 图片上传测试类 */ @Controller public class ImageUplodController { @RequestMapping(value = "upload.do") public Object uploadImage(MultipartFile upload, String CKEditorFuncNum) { // upload即图片文件可直接转换成字节数组存数据库或其他云空间 try { byte[] imageBytes = upload.getBytes(); } catch (IOException e) { e.printStackTrace(); } // 处理图片....返回一个图片的URL // code...... // 最后返回一个URL给ckeditor;其中image/imagePath.png为image存后的路径;第一个参数来自前台的一个标志,第三个参数错误返回码 return "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", 'image/imagePath.png', '');</script> "; //这里返回的JavaScript代码为ckeditor API中回调函数要求返回格式 } } </code></pre> <img alt="import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; /** * * * 图片上传测试类 */ @Controller public class ImageUplodController { @RequestMapping(value = "upload.do") public Object uploadImage(MultipartFile upload, String CKEditorFuncNum) { // upload即图片文件可直接转换成字节数组存数据库或其他云空间 try { byte[] imageBytes = upload.getBytes(); } catch (IOException e) { e.printStackTrace(); } // 处理图片....返回一个图片的URL // code...... // 最后返回一个URL给ckeditor;其中image/imagePath.png为image存后的路径;第一个参数来自前台的一个标志,第三个参数错误返回码 return "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", 'image/imagePath.png', '');</script> "; //这里返回的JavaScript代码为ckeditor API中回调函数要求返回格式 } }" class="img-thumbnail" src="/assist/images/blog/32e6798a-7fbc-4c01-8aa7-cf71e3fa9532.png" style="height:529px; width:493px" />