我在 Spring java 中做项目。需要在不使用表单提交的情况下上传图像并仅使用 jquery 的 ajax 调用(因为我需要在同一页面中处理图像)
我有type=file 的输入标签和
我已经在 spring maven 中加载了commons-fileupload、commons-io jar并且还添加了multipartResolver
现在我正在为 servlet 使用以下代码
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
Map<String, Object> map = Maps.newHashMap();
try {
BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File("C:/Users/XXX/Desktop/Image_files/Image1.png");
ImageIO.write(src, "png", destination);
} catch(Exception e) {
e.printStackTrace();
}
return map;
}
Run Code Online (Sandbox Code Playgroud)
我的js文件
$("#uploadbutton").on("click", function() {
var oMyForm = new FormData();
oMyForm.append("file", $("#imageid").prop("files")[0]);
$.ajax({
url: "/photo/upload/upload", …Run Code Online (Sandbox Code Playgroud)