SpringMVC 파일 업로드 방법 소개(코드)
이 글은 SpringMVC 파일 업로드 방법(코드)에 대한 소개를 담고 있습니다. 필요한 친구들이 참고할 수 있기를 바랍니다.
SpringMVC는 플러그 앤 플레이 MultipartResolver를 사용하여 구현되는 파일 업로드를 직접 지원합니다. SpringMVC는 Apache Commons FileUpload 기술을 사용하여 MultipartResolver 구현 클래스인 CommonsMultipartResolver를 구현합니다. 따라서 SpringMVC의 파일 업로드도 Apache Commons FileUpload 구성 요소에 의존해야 합니다.
1. pom 종속성 추가
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency>
2. 파일 업로드 빈 구성
Spring MVC 구성 파일에 파일 업로드 빈을 추가하세요.
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> </bean>
3. 파일 업로드
파일 업로드는 프로젝트 개발에서 가장 일반적인 기능입니다. 파일을 업로드하려면 양식 메소드를 POST로 설정하고 enctype을 multipart/form-data로 설정해야 합니다. 이 경우에만 브라우저는 사용자가 선택한 파일을 바이너리 데이터로 서버에 보냅니다.
파일 업로드 인터페이스: upload_form.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <!-- 上传单个对象 注意表单的method属性设为post,enctype属性设为multipart/form-data --> <form method="POST" action="/SpringMVCDemo1/upload" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="submit" value="上传" /> </form> <!-- 上传多个对象 注意表单的method属性设为post,enctype属性设为multipart/form-data --> <form method="POST" action="/SpringMVCDemo1/uploadMultiFiles" enctype="multipart/form-data"> <p>文件1:<input type="file" name="file" /></p> <p>文件2:<input type="file" name="file" /></p> <p>文件3:<input type="file" name="file" /></p> <!-- 同时传递其他业务字段 --> <p>用户名:<input type="text" name="userName" /></p> <p>密码:<input type="password" name="password" /></p> <p><input type="submit" value="上传" /></p> </form> </body> </html>
업로드 결과 반환 인터페이스: upload_result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <h2>上传结果为:${message}</h2> </body> </html>
참고: 미리 파일을 저장할 폴더를 만들어야 합니다. 예를 들어 내 경로는 "D:staticResourcesTestimgupload"입니다. .
FileController.java
@Controller @RequestMapping("/SpringMVCDemo1") public class FileController { /** * 跳转到上传页面 * @GetMapping 是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。 */ @GetMapping("/gotoUploadForm") public String index() { return "/upload_form.jsp"; } /** * 上传单个文件 * 通过MultipartFile读取文件信息,如果文件为空跳转到结果页并给出提示; * 如果不为空读取文件流并写入到指定目录,最后将结果展示到页面 * @param multipartFile * @PostMapping 是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。 */ @PostMapping("/upload") public String uploadSingleFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){ if (multipartFile.isEmpty()){ request.setAttribute("message", "Please select a file to upload '"); return "/upload_result.jsp"; } try { String contentType = multipartFile.getContentType(); String originalFilename = multipartFile.getOriginalFilename(); byte[] bytes = multipartFile.getBytes(); System.out.println("上传文件名为-->" + originalFilename); System.out.println("上传文件类型为-->" + contentType); System.out.println("上传文件大小为-->"+bytes.length); //filePath为存储路径 String filePath = "d:/staticResourcesTest"; System.out.println("filePath-->" + filePath); //存储在staticResourcesTest下的imgupload文件夹下 File parentPath = new File(filePath, "imgupload"); System.out.println("上传目的地为-->"+parentPath.getAbsolutePath()); try { File destFile = new File(parentPath,originalFilename);//上传目的地 FileUtils.writeByteArrayToFile(destFile,multipartFile.getBytes()); } catch (Exception e) { e.printStackTrace(); } request.setAttribute("message", "You successfully uploaded '" + multipartFile.getOriginalFilename() + "'"); } catch (IOException e) { e.printStackTrace(); } return "/upload_result.jsp"; } /** * 上传多个文件,同时接受业务数据 * @param origFiles * @param request * @param user * @return */ @PostMapping("/uploadMultiFiles") public String uploadMultiFiles(@RequestParam("file") List<MultipartFile> origFiles, HttpServletRequest request, User user) { //User为实体类 System.out.println("User=="+user); if (origFiles.isEmpty()) { request.setAttribute("message", "Please select a file to upload '"); return "/upload_result.jsp"; } try { for (MultipartFile origFile : origFiles) { String contentType = origFile.getContentType(); String fileName = origFile.getOriginalFilename(); byte[] bytes = origFile.getBytes(); System.out.println("上传文件名为-->" + fileName); System.out.println("上传文件类型为-->" + contentType); System.out.println("上传文件大小为-->"+bytes.length); String filePath = "d:/staticResourcesTest"; System.out.println("上传目的地为-->"+filePath); try { //上传目的地(staticResourcesTest文件夹下) File destFile = new File(filePath,fileName); FileUtils.writeByteArrayToFile(destFile,origFile.getBytes()); } catch (Exception e) { e.printStackTrace(); } } request.setAttribute("message", "You successfully uploaded '"); } catch (IOException e) { e.printStackTrace(); } return "/upload_result.jsp"; } }
이 기사는 여기서 끝났습니다. 더 많은 흥미로운 콘텐츠를 보려면 PHP 중국어 웹사이트의 Java Tutorial Video 칼럼을 참조하세요.
위 내용은 SpringMVC 파일 업로드 방법 소개(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











자바의 암스트롱 번호 안내 여기에서는 일부 코드와 함께 Java의 Armstrong 번호에 대한 소개를 논의합니다.

Java의 난수 생성기 안내. 여기서는 예제를 통해 Java의 함수와 예제를 통해 두 가지 다른 생성기에 대해 설명합니다.

Java의 Weka 가이드. 여기에서는 소개, weka java 사용 방법, 플랫폼 유형 및 장점을 예제와 함께 설명합니다.

Java의 Smith Number 가이드. 여기서는 정의, Java에서 스미스 번호를 확인하는 방법에 대해 논의합니다. 코드 구현의 예.

이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다
