这里笔者介绍利用SpringMVC上传图片的操作。

1.  引入jar文件

不仅需要导入开发SpringMVC相关的包,还需要导入 commons-fileupload-1.2.1.jar 和 commons-io-1.3.2.jar

2.  配置applicationContext.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

3.  编写html文件:

        需要注意: 提交文件, 只能使用POST方式, 并且要指定enctype="multipart/form-data"
例如:

    <form action="file.do" method="POST" enctype="multipart/form-data">
        请选择您要上传的文件:<br><br>
        <input type="file" name="file"/><br>
        <input type="submit"/>
    </form>

4.  编写接收上传文件的Controller了  ,接收的文件的类型: MultipartFile

    例如:

@RequestMapping("/file.do")
public String fileUpload(MultipartFile file){
    //上传的文件: file
    System.out.println("上传的文件名称为:"+file.getOriginalFilename());
    return "result";
}

Demo

下面是一个接受上传图片的Demo,该Demo能够把用户上传的图片存储到部署项目的根目录下面。那么如何查看自己项目的根目录:点击 项目->.metadata->.plugins->org.eclipse.wst.server.core->tmp0->wtpwebapps ,在里面就可以看到部署的项目了。

【Spring】SpringMVC之上传文件

jsp文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    文件上传成功:${imagePath }
</body>
</html>
fileUploadOk.jsp

相关文章: