把一个文件上传到本地文件夹
package com.baic.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传
*
* @author wuyahui
*
*/
public class Upload2Local {
private static Logger logger = LoggerFactory.getLogger(Upload2Local.class);
public static String upload(MultipartFile multipartFile, String filePath) {
String localPath = "";
try {
// 将文件上传到指定盘upload文件夹下
File file = new File(filePath);
// 如果文件夹不存在则创建
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
String path = filePath;
String filename = multipartFile.getOriginalFilename();
// 如果服务器已经存在和上传文件同名的文件,则输出提示信息
InputStream is = multipartFile.getInputStream();
File tempFile = new File(path + filename);
if (tempFile.exists()) {
boolean delResult = tempFile.delete();
System.out.println("删除已存在的文件:" + delResult);
}
// 开始保存文件到服务器
if (!filename.equals("")) {
FileOutputStream fos = new FileOutputStream(path + filename);
// 每次读8K字节
byte[] buffer = new byte[8192];
int count = 0;
// 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
while ((count = is.read(buffer)) > 0) {
// 向服务端文件写入字节流
fos.write(buffer, 0, count);
}
// 关闭FileOutputStream对象
fos.close();
// InputStream对象
is.close();
}
localPath = path + filename;
} catch (Exception e) {
logger.error("上传文件到本地", e);
}
return localPath;
}
}