[SpringBoot+Html]实现简单的文件上传并存储至本地,含前后端代码
后端SpringBoot代码:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空,请选择有效文件上传。";
}
try {
String uploadDirectory = System.getProperty("user.dir") + "/uploads/";
File directory = new File(uploadDirectory);
if (!directory.exists()) {
directory.mkdirs();
}
String filePath = uploadDirectory + file.getOriginalFilename();
file.transferTo(Paths.get(filePath));
return "文件上传成功:" + filePath;
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败:" + e.getMessage();
}
}
}
前端HTML和JavaScript代码:
<!DOCTYPE html>
<html>
<head>
<title>文件上传示例</title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<button type="button" onclick="uploadFile()">上传文件</button>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
function uploadFile() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
alert(response);
},
error: function() {
alert('文件上传失败');
}
});
}
</script>
</body>
</html>
在这个例子中,前端使用HTML定义了一个文件上传表单,并通过JavaScript使用FormData对象和Ajax请求发送文件到后端。后端SpringBoot应用通过@RestController
和@PostMapping
注解处理文件上传请求,并保存文件到服务器的uploads
目录下。
评论已关闭