后端代码:标红的地方为出错的地方,经检查发现是在写文件的时候,没有指定文件名称,只是给了一个写文件的路径,不知道上传的对应的流应该写在什么地方,所以保存。
@Controller
public class UploadFileController {
//private static String path = "D:/ideaworkspace/demo-11/demo-11/src/main/resources/static/image/";
private static String path = "D:/555/";
@RequestMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file_name")MultipartFile file, HttpServletRequest request){
String username = ("username");
("用户名:"+username);
String filename = ();
("上传文件的名称:"+filename);
//获取文件的后缀名
String suffixName = ();
(suffixName);
//后缀名称
String a[] = (".");
for(int i=0;i<;i++){
(a[i]);
}
();
(((".")));
filename = ()+(("."));
File newFile = new File(path);
修改为下列代码即可:
File newFile = new File(path+filename);
try {
(newFile); //拷贝文件,性能高效,比原先的方便
return filename;
} catch (IOException e) {
();
}
return "上传失败";
}
}
前端代码,重点是要添加enctype="multipart/form-data":
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<h1>测试文件上传</h1>
<form name="upload" action="/upload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file_name" />
姓名:<input type="text" name="username"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>