W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
當(dāng)解析器MultipartResolver
完成處理時(shí),請(qǐng)求便會(huì)像其他請(qǐng)求一樣被正常流程處理。首先,創(chuàng)建一個(gè)接受文件上傳的表單將允許用于直接上傳整個(gè)表單。編碼屬性(enctype="multipart/form-data"
)能讓瀏覽器知道如何對(duì)多路上傳請(qǐng)求的表單進(jìn)行編碼(encode)。
<html>
<head>
<title>Upload a file please</title>
</head>
<body>
<h1>Please upload a file</h1>
<form method="post" action="/form" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
下一步是創(chuàng)建一個(gè)能處理文件上傳的控制器。這里需要的控制器與一般注解了@Controller
的控制器基本一樣,除了它接受的方法參數(shù)類(lèi)型是MultipartHttpServletRequest
,或MultipartFile
。
@Controller
public class FileUploadController {
@RequestMapping(path = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
}
return "redirect:uploadFailure";
}
}
請(qǐng)留意@RequestParam
注解是如何將方法參數(shù)對(duì)應(yīng)到表單中的定義的輸入字段的。在上面的例子中,我們拿到了byte[]
文件數(shù)據(jù),只是沒(méi)對(duì)它做任何事。在實(shí)際應(yīng)用中,你可能會(huì)將它保存到數(shù)據(jù)庫(kù)、存儲(chǔ)在文件系統(tǒng)上,或做其他的處理。
當(dāng)使用Servlet 3.0的多路傳輸轉(zhuǎn)換時(shí),你也可以使用javax.servlet.http.Part
作為方法參數(shù):
@Controller
public class FileUploadController {
@RequestMapping(path = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") Part file) {
InputStream inputStream = file.getInputStream();
// store bytes from uploaded file somewhere
return "redirect:uploadSuccess";
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話(huà):173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: