後端代碼:標紅的地方爲出錯的地方,經檢查發現是在寫文件的時候,沒有指定文件名稱,只是給了一個寫文件的路徑,不知道上傳的對應的流應該寫在什麼地方,所以保存。
@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 = request.getParameter("username");
System.out.println("用戶名:"+username);
String filename = file.getName();
System.out.println("上傳文件的名稱:"+filename);
//獲取文件的後綴名
String suffixName = file.getOriginalFilename();
System.out.println(suffixName);
//後綴名稱
String a[] = suffixName.split(".");
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
System.out.println();
System.out.println(suffixName.substring(suffixName.indexOf(".")));
filename = UUID.randomUUID()+suffixName.substring(suffixName.indexOf("."));
File newFile = new File(path);
修改爲下列代碼即可:
File newFile = new File(path+filename);
try {
file.transferTo(newFile); //拷貝文件,性能高效,比原先的方便
return filename;
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}
}
前端代碼,重點是要添加enctype="multipart/form-data":
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上傳</title>
</head>
<body>
<h1>測試文件上傳</h1>
<form id="upload" 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>