1. 文件上传。
(1)普通本地服务器上传。
(2)ajax本地服务器上传。
(3) 普通oss服务器上传。
(4) ajax的oss服务器上传。
【1】表单必须是post提交 编码方式必须是二进制编码。 input type=file name="必须有该属性名"
[2] processData: false contentType: false查看所有请点此处A_M阿木的博客_CSDN博客-领域博主
1、ajax本地上传
前端:代码
<%--
Created by IntelliJ IDEA.
User: am
Date: 2021/12/7
Time: 9:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>
</head>
<body>
<form id="userForm">
头像:<input type="file" name="myfile"/><br>
姓名:<input type="text" name="name"/><br>
性别:<input type="text" name="sex"/><br>
<input type="button" id="btn" value="提交"/>
</form>
<img id="headImg"/>
<script>
$("#btn").click(function(){
var formData = new FormData(document.getElementById("userForm")); //获取表单数据
$.ajax({
url:"${pageContext.request.contextPath}/upload2",
type:"post",
processData: false,
contentType: false,// 设置表单的编码格式为二进制格式。 默认
data: formData,
success: function(result){
if(result.code===2000){
$("#headImg").attr("src",result.imgSrc);
}
},
dataType: "json"
})
});
后台代码:
package com.am.controller;
import com.am.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @program: springmvc-upload
* @description:
* @author: 阿木
* @create: 2021-12-07 11:04
**/
@Controller
public class UploadController2 {
@RequestMapping("/upload2")
@ResponseBody
public Map<String,Object> upload2(MultipartFile myfile, HttpServletRequest request, User user){
Map<String,Object> map=new HashMap<String, Object>();
//1.获取保存的真实路径
String path = request.getSession().getServletContext().getRealPath("upload");
//2.根据真实路径封装文件File对象
File file=new File(path);
if(!file.exists()){
file.mkdirs();
}
//3.获取文件的名称
String filename=myfile.getOriginalFilename();
filename=new Date().getTime()+filename;
//4. 文件存方在真实的路径下
File target=new File(path+"/"+filename);
try {
myfile.transferTo(target);//保存
map.put("code",2000);
map.put("msg","上传成功");
map.put("imgSrc","http://localhost:8080/springmvc_upload/upload/"+filename);
return map;
} catch (IOException e) {
e.printStackTrace();
}
map.put("code",5000);
map.put("msg","上传失败");
return map;
}
}