ajax上传单个文件
jsp页面
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <script type="text/javascript" src="./js/jquery-3.5.1.min.js"></script> <script type="text/javascript" src="./js/vue.js"></script> <title>文件上传</title> </head> <body> <input type="file" id="UUploadedFile" name="fileupload" onchange="UUploadedFile()"> <script type="text/javascript"> function UUploadedFile() { var formData = new FormData(); formData.append('file', $('#UUploadedFile')[0].files[0]); $.ajax({ async: false,//要求同步 不是不需看你的需求 url : "${pageContext.request.contextPath}/TestuploadFile.do", type : 'POST', data : formData, dataType: "json", processData : false, //必须false才会避开jQuery对 formdata 的默认处理 contentType : false, //必须false才会自动加上正确的Content-Type success: function (data) { if (data.success ) { alert("上传完成!"); }else{ alert("上传失败!"); } }, }); } </script> </body> </html>
//java后端代码
package com.zjn.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; @Controller public class FileUpload { @RequestMapping(value = "/TestuploadFile.do") @ResponseBody public Map<String, Object> TestuploadFile(HttpServletRequest request){ Map<String, Object> modelMap=new HashMap<String, Object>(); try { MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request; MultipartFile file = mpRequest.getFile("file"); System.out.println("file===="+file); long fileSize = file.getSize();//获取文件大小 if (fileSize <= 0) { modelMap.put("success", false); modelMap.put("MESSAGE", "上传失败!上传的文件为空!"); return modelMap; } if (fileSize > 200 * 1024 * 1024) {//限制上传文件大小为200M modelMap.put("success", false); modelMap.put("MESSAGE", "上传失败!上传的文件大小超出了限制!"); return modelMap; } InputStream in = file.getInputStream();//读取上传的文件流 OutputStream out = new FileOutputStream("D:/"+file.getOriginalFilename()); File outFile=new File("D:/"+file.getOriginalFilename());//把文件输出到D盘下 byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); if(outFile.exists()){//判断文件是否存在 modelMap.put("success", true); modelMap.put("MESSAGE", "上传完成!"); }else { modelMap.put("success", false); modelMap.put("MESSAGE", "上传失败!"); return modelMap; } } catch (IOException e) { modelMap.put("success", false); modelMap.put("MESSAGE", "上传失败!"); return modelMap; } return modelMap; } }