1、导入依赖
<!-- 文件上传组件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 时间操作组件 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.5</version>
</dependency>
2、在SpringMVC配置文件中添加文件上传解析器
<!-- 定义文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
3、resource.properties
FTP_SERVER_IP=172.20.10.8
FTP_SERVER_PORT=21
FTP_SERVER_USERNAME=ftpuser
FTP_SERVER_PASSWORD=123456
FTP_BASE_PATH=/home/ftpuser/www/images
IMAGE_BASE_URL=http://172.20.10.8/images
4、PictureService
import org.springframework.web.multipart.MultipartFile;
public interface PictureService {
PictureResult uploadFile(MultipartFile uploadFile);
}
@Service
public class PictureServiceImpl implements PictureService {
@Value("${IMAGE_BASE_URL}")
private String IMAGE_BASE_URL;
@Value("${FTP_BASE_PATH}")
private String FTP_BASE_PATH;
@Value("${FTP_SERVER_IP}")
private String FTP_SERVER_IP;
@Value("${FTP_SERVER_PORT}")
private Integer FTP_SERVER_PORT;
@Value("${FTP_SERVER_USERNAME}")
private String FTP_SERVER_USERNAME;
@Value("${FTP_SERVER_PASSWORD}")
private String FTP_SERVER_PASSWORD;
@Override
public PictureResult uploadFile(MultipartFile uploadFile) {
String path = savePicture(uploadFile);
int code = path.startsWith("error") ? 1 : 0;
PictureResult result = new PictureResult(code, IMAGE_BASE_URL + path);
return result;
}
private String savePicture(MultipartFile uploadFile) {
String result = "";
if (uploadFile.isEmpty()) {
return null;
}
try {
String oldFileName = uploadFile.getOriginalFilename();
String newFileName = IDUtils.genImageName() + oldFileName.substring(oldFileName.lastIndexOf("."));
//要上传到服务器的哪个目录
String filePath = DateTime.now().toString("/yyyy/MM/dd");
boolean b = FtpUtil.uploadFile(FTP_SERVER_IP, FTP_SERVER_PORT, FTP_SERVER_USERNAME, FTP_SERVER_PASSWORD,
FTP_BASE_PATH, filePath, newFileName, uploadFile.getInputStream());
if (b) {
result = filePath + "/" + newFileName;
} else {
result = "error:上传失败";
}
} catch (Exception e) {
e.printStackTrace();
result = "error:" + e.getMessage();
}
return result;
}
}
5、PictureController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/pic")
public class PictureController {
@Autowired
private PictureService service;
@RequestMapping("/upload2")
@ResponseBody
public PictureResult upload(MultipartFile uploadFile) {
PictureResult result = service.uploadFile(uploadFile);
return result;
}
@RequestMapping("/upload")
@ResponseBody
public String upload2(MultipartFile uploadFile) {
PictureResult result = service.uploadFile(uploadFile);
//为了保证功能的兼容性,需要把Result转换成json格式的字符串。
String json = JsonUtils.objectToJson(result);
return json;
}
}
6、其它
使用FTPClient上传文件
public class PictureResult {
/**
* 上传图片返回值,成功:0 失败:1
*/
private Integer error;
/**
* 回显图片使用的url
*/
private String url;
/**
* 错误时的错误消息
*/
private String message;
public PictureResult(Integer state, String url) {
this.url = url;
this.error = state;
}
public PictureResult(Integer state, String url, String errorMessage) {
this.url = url;
this.error = state;
this.message = errorMessage;
}
public Integer getError() {
return error;
}
public void setError(Integer error) {
this.error = error;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
/**
* 图片名生成
*/
public static String genImageName() {
//取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
//long millis = System.nanoTime();
//加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
//如果不足三位前面补0
String str = millis + String.format("%03d", end3);
return str;
}