前台用ajax上传文件到服务器

前台用ajax上传文件到服务器

html:

<form id="uploadForm" enctype="multipart/form-data">
  文件:<input id="file" type="file" name="file" />
</form>
<button id="upload">上传文件</button>

扩展:
enctype:规定在发送到服务器之前如何对表单数据进行编码

描述
application/x-www-form-urlencodeed 在发送前编码所有字符(默认)
multipart/form-data 不对字符编码
在使用包含文件上传表单时,必须使用该值
text/plain 空格转换为“+”加号,但不对特殊字符编码

js:

$("#upload").click(function(){
  var formData = new FormData($("#com-info-alter-form")[0]);
                    //确定提交
                    $.ajax({
                        url: url+"alter/com-info-alter-submit",
                        type: 'post',
                        data: formData,
                        async: false,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (msg) {
                        },
                      	error: function(msg){
                        }
}
                   

扩展:
async
类型:Boolean
默认值:true。默认设置下,所有请求都是异步请求。如果需要发送同步请求,将该项设置为false
注意,同步请求将锁住浏览器,用户的其他操作必须等待请求完成才可以执行
cache
类型:Boolean
默认值: true,dataType 为 script 和 jsonp 时默认为 false。设置为 false 将不缓存此页面。
jQuery 1.2 新功能
contentType
类型:String
默认值: “application/x-www-form-urlencoded”。发送信息至服务器时内容编码类型。
默认值适合大多数情况。如果你明确地传递了一个 content-type 给 $.ajax() 那么它必定会发送给服务器(即        使没有数据要发送)。
processData
类型:Boolean
默认值: true。默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会       处理转化成一个查询字符串,以配合默认内容类型 “application/x-www-form-urlencoded”。如果要发送           DOM     树信息或其它不希望转换的信息,请设置为 false。

controller:

	@ResponseBody
    @RequestMapping("/com-info-alter-submit")
    public Msg comInfoAlterSubmit(@RequestParam("file") MultipartFile file){
    	
    }

参考博客:

https://blog.csdn.net/huxiangen/article/details/84970394

发布了15 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/BrotherBear2008/article/details/104258230
今日推荐