Springmvc实现图片上传功能
1.我们要设置图片解析
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>5000000</value>
</property>
</bean>
2.把图片解析器依赖的jar包导入项目
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>${common-io.version}</version>
</dependency>
3.编写上传文件的页面
<%--上传文件的页面中的表单必须设置enctype,且值必须为 multipart/form-data--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传文件</title>
</head>
<body>
<form action="fileUpLoad" method="post" enctype="multipart/form-data">
<input type="file" name="filename" >
<button>上传</button>
</form>
</body>
</html>
4.编写上传文件的核心代码
package com.ty.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
@Controller
public class UpLoadFileController {
@RequestMapping("/fileUpLoad")
public void upLoadFile(MultipartFile filename) {
if (filename != null) {
String originalFilename = filename.getOriginalFilename();
if (originalFilename != null && originalFilename.length() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String newFileName = sdf.format(new Date()) + "/" + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
File saveFile = new File("d:/image/" + newFileName);
if (!saveFile.exists()) {
saveFile.mkdirs();
}
try {
filename.transferTo(saveFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}