java文件上传(单文件 多文件)与删除
/**
* 文件上传--单文件
*
* @param request
* @param response
* @param path
* 文件存放路径(path为WebApp\后面的内容)
* @return
*/
public final static String fileUpload(HttpServletRequest request,
HttpServletResponse response, String path) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
MultipartFile mFile = null;
for (Iterator<?> i = fileMap.keySet().iterator(); i.hasNext();) {
Object obj = i.next();
mFile = (MultipartFile) fileMap.get(obj);
}
String filePath = "";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
try {
// 得到上传的文件的文件名
String filename = mFile.getOriginalFilename();
// 获取文件后缀名
if (filename != null && !("").equals(filename)) {
String fileExt = filename.substring(filename.lastIndexOf("."));
// 按时间格式重新生成文件名
String newFileName = sdf.format(new Date())
+ (int) (Math.random() * 100) + fileExt;
filePath = path + "/" + newFileName;
// 得到上传服务器的物理路径
path = request.getSession().getServletContext()
.getRealPath("\\" + path);
// 文件流写到服务器端
File saveFile = new File(path, newFileName);
FileCopyUtils.copy(mFile.getBytes(), saveFile);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return filePath;
}
/**
* 文件上传--多文件
*
* @param request
* @param response
* @param filePaths
* (fileinputId,WebApp\后面的内容)
* @return
*/
public final static Map<String, Object> fileUploads(
HttpServletRequest request, HttpServletResponse response,
String path) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
Map<String, Object> filePaths = new HashMap<String, Object>();
// 得到上传服务器的物理路径
String fileUrl = request.getSession().getServletContext()
.getRealPath("\\" + path);
for (Iterator<?> i = fileMap.keySet().iterator(); i.hasNext();) {
Object obj = i.next();
MultipartFile mFile = (MultipartFile) fileMap.get(obj);
// 得到上传的文件的文件名
String filename = mFile.getOriginalFilename();
if (filename == "" || filename == null) {
continue;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
// 获取文件后缀名
String fileExt = filename.substring(filename.lastIndexOf("."));
// 按时间格式重新生成文件名
String newFileName = sdf.format(new Date())
+ (int) (Math.random() * 100) + fileExt;
String filePath = path + "/" + newFileName;
// 文件流写到服务器端
try {
filePaths.put(obj.toString(), filePath);
File saveFile = new File(fileUrl, newFileName);
FileCopyUtils.copy(mFile.getBytes(), saveFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return filePaths;
}
/**
* 删除文件,
*
* @param request请求
* @param filePath文件路径
* (static/upload/...)
* @return
*/
public static boolean fileDelete(HttpServletRequest request, String filePath) {
String fileUrl = request.getSession().getServletContext()
.getRealPath("\\" + filePath);// 得到上传服务器的物理路径
File file = new File(fileUrl);
fileDelete(file);
return false;
}