使用jQuery ajax 上传文件

一,文件上传控制层(springmvc)
import java.io.File;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.alibaba.fastjson.JSONObject;

@RestController
@RequestMapping("/file")
public class FileController {

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Object upload(@RequestParam(value = "uploadfile", required = false) MultipartFile file, String other) {
		JSONObject json = new JSONObject();
		try {
			if (file != null) {
				String path = "F:/test/upload/";
				file.transferTo(new File(path + file.getOriginalFilename()));
			}
			json.put("success", "true");
			json.put("message", "提交成功!");
			json.put("data", other);
		} catch (Exception e) {
			json.put("success", "true");
			json.put("message", "上传失败!" + e.getMessage());
			json.put("data", other);
		}
		return json;
	}
	
}
二,html与js
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.box{
				width: 500px;
				margin: 50px auto;
				text-align: center;
			}
			.box div{
				line-height: 40px;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<form action="javascript:;" method="post" enctype="multipart/form-data">
				<div>other:<input name="other" id="other" /></div>
				<div><input type="file" id="uploadfile" name="uploadfile" /></div>
				<div><input type="submit" id="sub" value="提交" /></div>
			</form>
		</div>
		<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
		<script>
			$("#sub").click(function() {
				var files = $("#uploadfile").prop("files");
				var data = new FormData();
				data.append("uploadfile", files[0]);
				data.append("other", $("#other").val());

				$.ajax({
					type: 'POST',
					url: "/file/upload",
					data: data,
					dataType:"json",
					cache: false,//不使用缓存
					processData: false,//不序列化
					contentType: false,//避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件
					success: function(data) {
						if(data.success){
							$("#uploadfile").val("");
							$("#other").val("");
						}
						alert(data.message);
						alert("other:" + data.data);
					}
				});
			});
		</script>
	</body>
</html>
三,实现效果

在这里插入图片描述

在这里插入图片描述

注:使用的式例为springboot项目

猜你喜欢

转载自blog.csdn.net/weixin_39806100/article/details/86619508