文件上传公共方法
1.[代码][Java]代码
import java.io.File;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传公共方法
*
* @author chinda
*
*/
public class FileUtil {
private static Logger logger = LoggerFactory.getLogger(FileUtil.class);
// 上传文件,并更新app_uploads表
public static AppUploads uploadFile(MultipartFile file, HttpServletRequest request, AppUploads appUploads) {
// 获取存放文件的文件夹
// String path =
// request.getSession().getServletContext().getRealPath("");
String path = PropertyFileUtil.get("uploadPath");//"D:\\tomcat\\uploads";
// 获取上传文件的名称
String fileName = file.getOriginalFilename();
File targetFile = new File(path, fileName);
int x = fileName.lastIndexOf(".");
String name = fileName.substring(0, x);
String type = fileName.substring(x + 1);
// 判断文件夹是否存在
if (!targetFile.exists()) {
targetFile.mkdirs();
} else {
String newName = name + "_1";
targetFile = new File(path, newName + "." + type);
for (int i = 2; targetFile.exists(); i++) {
newName = name + "_" + i;
targetFile = new File(path, newName + "." + type);
}
name = newName;
fileName = newName + "." + type;
}
try {
// 保存上传文件
file.transferTo(targetFile);
logger.info(fileName + "上传文件成功!");
appUploads.setFilePath(path);
appUploads.setFileName(name);
appUploads.setFileType(type);
appUploads.setUploadDate(new Date());
return appUploads;
} catch (Exception e) {
e.printStackTrace();
logger.info(fileName + "上传文件失败!");
return null;
}
}
// 删除文件
public static boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
}