ajax 单文件 多文件 上传

使用 ajax 上传文件,页面不刷新

本文后台使用 springboot 框架

 

后台上传接口

package com.che.pri.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileUpdateController {
	
	/**
	 * 多文件上传
	 * @param request
	 * @param files
	 * @return
	 */
	@RequestMapping(value="/uploads")
	public Object filesUpload(HttpServletRequest request, MultipartFile[] files) {
		Map<String, String> res = new HashMap<String, String>();
		
		String str= request.getServletContext().getRealPath("/images/file/");
		
		for(int i=0; i<files.length; i++) {
			System.out.println(files[i].getOriginalFilename());
			
			File newFile = new File(str, files[i].getOriginalFilename());
			if(!newFile.getParentFile().exists()) {
				newFile.getParentFile().mkdirs();
			}
			try {
				files[i].transferTo(newFile);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		    //返回原文件名
			res.put("" + i, files[i].getOriginalFilename());
		}
		return res;
	}

	/**
	 * 单文件上传
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/upload")
	public String FileUpdate(HttpServletRequest request,MultipartFile file) {
	   String str= request.getServletContext().getRealPath("/images/");
	   
	   String originalname=file.getOriginalFilename();
	   System.out.println(originalname);
	   System.out.println(str);
	   File newFile=new File(str,originalname);
	   
	   if(!newFile.getParentFile().exists()) {
		   newFile.getParentFile().mkdirs();
	   }
	   try {
		file.transferTo(newFile);
	} catch (IllegalStateException | IOException e) {
	
		e.printStackTrace();
	}
	   return originalname;
	}
	
}

 

单文件上传 html 

<!--ajax 单文件上传-->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="file" name="file"/>
        </form>
        <button id="uploadButton">上传文件</button>
        <script>
            $("#uploadButton").click(function(){
                var formData = new FormData($("#uploadForm")[0]);
                $.ajax({
                    type:"post",
                    url:"http://localhost:8089/file/upload",
                    async:true,
                    data:formData,
                    cache:false,
                    processData: false,
                    contentType: false,
                    success:function(res){
                        alert(res)
                    }
                });
            });
        </script>
    </body>
</html>

 

多文件上传 html

<!--ajax 多文件上传-->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
    </head>
    <body>
        <form id="uploadForm" enctype="multipart/form-data">
            <input type="file" name="files" multiple="multiple" />
        </form>
        <button id="uploadButton">上传文件</button>
        <script>
            $("#uploadButton").click(function(){
                var formData = new FormData($("#uploadForm")[0]);
                $.ajax({
                    type:"post",
                    url:"http://localhost:8089/file/uploads",
                    async:true,
                    data:formData,
                    cache:false,
                    processData: false,
                    contentType: false,
                    success:function(res){
                        alert(res)
                    }
                });
            });
        </script>
    </body>
</html>

仔细对比会发现 多文件上传比单文件上传多了 multiple="multiple" 属性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟世君子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值