<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean> html <form action="/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> @Controller public class FileUploadController { @RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFileUpload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // ... } catch (IOException e) { e.printStackTrace(); } } } } @Controller public class FileDownloadController { @RequestMapping(value = "/download", method = RequestMethod.GET) public void handleFileDownload(HttpServletRequest request, HttpServletResponse response) throws IOException { File file = new File(filePath); if (file.exists()) { response.setContentType("application/octet-stream"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); try (InputStream inputStream = new FileInputStream(file); OutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } else { } } }


上一篇:
下一篇:
切换中文