htmlファイル
src/main/resources/public/file-upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css">
</head>
<body>
<div class="">
<form id="form" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="button" id="upload" value="upload"></p>
</form>
<span id="result" style="padding:3px"></span>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<script>
$(function(){
$('#upload').click(function(){
var formData = new FormData(
$('#form').get()[0]
);
$.ajax({
url:'/upload',
method:'post',
data:formData,
processData:false,
contentType:false,
cache: false
}).done(function(data,status,jqxhr){
$('#result').text('結果: 成功');
}).fail(function(data, status, jqxhr){
$('#result').text('結果: 失敗');
});
});
});
</script>
</body>
</html>
Controller
package com.example.demo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.FileCopyUtils;
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;
@RestController
public class HelloController {
@RequestMapping(value="/upload", method=RequestMethod.POST)
public void handle(
HttpServletResponse response,
@RequestParam MultipartFile file
) {
if(file.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
try {
BufferedInputStream in = new BufferedInputStream(file.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(file.getOriginalFilename()));
} catch (IOException e) {
throw new RuntimeException("Error uploading file.", e);
}
}
publicに置くと、routingしなくて良いのか。。


ほう、こんなんなってるのか。。