今天要实现一个带token认证的文件上传 参数中既有token 也有文件流
首先上html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传测试</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<h1>文件上传测试</h1>
<form action="/moonstore-app/common/upload" method="post" enctype="multipart/form-data">
<p><input type="file" id="file" name="file"></p>
<p><input type="text" id="token" name="token" placeholder="token"></p>
<p><input type="button" onclick="upload()" value="submit"></p>
</form>
</body>
</html>
<script>
function upload() {
var file = $('#file')[0].files[0];
var token = $.trim($('#token').val());
var formData = new FormData();
formData.file = file;
formData.token = token;
formData.append("file",$('#file')[0].files[0]);
formData.append("token", token);
$.ajax({
url: '/moonstore-app/common/upload',
dataType: 'json',
type: 'POST',
async: false,
data: formData,
processData: false, // 使数据不做处理
contentType: false, // 不要设置Content-Type请求头
success: function (data) {
console.log(data);
if (data.responseCode == 200) {
alert('上传成功!');
}
},
error: function (response) {
console.log(response);
}
});
}
</script>
然后是后端的文件上传代码,后端我是用了springboot框架:
@PostMapping("/upload")
public RestResponse upload(TokenParam tokenParam, @RequestParam("file") MultipartFile[] file) {
if (ArrayUtils.isEmpty(file)) {
return RestResponse.error(ResultCode.FILE_IS_EMPTY);
} else {
List<FileVo> fileVoList = new ArrayList();
MultipartFile[] files = file;
int fileLength = file.length;
for (int i = 0; i < fileLength; i++) {
MultipartFile multipartFile = files[i];
if (!multipartFile.isEmpty()) {
String fileName = multipartFile.getOriginalFilename();
String filePath = "";
try {
filePath = UploadUtils.uploadToDfs(multipartFile.getInputStream(), fileName);
} catch (IOException e) {
log.error("文件上传异常:", e);
return RestResponse.error(ResultCode.FILE_UPLOAD_FAIL);
}
FileVo fileVo = new FileVo();
fileVo.setFileName(fileName);
fileVo.setFilePath(filePath);
fileVoList.add(fileVo);
}
}
return RestResponse.ok(fileVoList);
}
}
一些实体类:
@Getter
@Setter
public class FileVo {
private String fileName;
private String filePath;
}
@Getter
@Setter
public class TokenParam {
private String token;
private UserInfo userInfo;
private Integer moonStoreId;
}
RestResponse 是统一返回类
@Component
public class RestResponse<T> extends ResponseBean implements Serializable {
@Autowired(
required = false
)
protected StatusComponent statusComponent;
protected static StatusComponent component = new HttpStatusComponent();
@PostConstruct
public void init() {
if (null != this.statusComponent) {
component = this.statusComponent;
}
}
public RestResponse(boolean isSuccess, int responseCode, String responseMsg, Object data) {
super(isSuccess, responseCode, responseMsg, data);
}
public RestResponse() {
super(true, component.getStatus(), ResultCode.OK.getMessage(), (Object)null);
}
public RestResponse(T result) {
super(true, component.getStatus(), ResultCode.OK.getMessage(), result);
}
@JsonGetter("isSuccess")
public boolean getIsSuccess() {
return ResultCode.OK.getCode() == super.getResponseCode() || super.getResponseCode() == 0;
}
public static <T> RestResponse<T> ok() {
return (new RestResponse.DefaultBuilder()).build();
}
public static <T> RestResponse<T> ok(T result) {
return (new RestResponse.DefaultBuilder()).body(result);
}
public static <T> RestResponse<T> error(Code code) {
return (new RestResponse.DefaultBuilder()).status(code);
}
public static <T> RestResponse<T> error(SystemRuntimeException e) {
return (new RestResponse.DefaultBuilder()).status(e);
}
public static <T> RestResponse<T> error(String errorMessage) {
return (new RestResponse.DefaultBuilder()).status(errorMessage);
}
private static class DefaultBuilder<T> {
private DefaultBuilder() {
}
public <T> RestResponse<T> build() {
return this.body((Object)null);
}
public <T> RestResponse<T> body(T body) {
return new RestResponse(body);
}
public <T> RestResponse<T> status(Code code) {
RestResponse restApiResponse = new RestResponse();
restApiResponse.setResponseCode(code.getCode());
restApiResponse.setResponseMsg(code.getMessage());
return restApiResponse;
}
public <T> RestResponse<T> status(SystemRuntimeException e) {
RestResponse restApiResponse = new RestResponse();
restApiResponse.setResponseCode(e.getCode().getCode());
restApiResponse.setResponseMsg(e.getMessage());
return restApiResponse;
}
public <T> RestResponse<T> status(String errorMessage) {
RestResponse restApiResponse = new RestResponse();
restApiResponse.setResponseCode(ResultCode.INTERNAL_SERVER_ERROR.getCode());
restApiResponse.setResponseMsg(errorMessage);
return restApiResponse;
}
}
}
ResultCode是常量提示返回枚举 这个我就不上了