javaweb controller中上传怎么写
展开全部
一般可以封装一个工具类统一调用:
spring mvc 上传:
/**
* 上传文件(单个文件)
* @param request req请求
* @param destPath 文件保存路径
* @return 上传后文件名
* 注意:uploadFile 为 前端 input file 的name属性
*/
public static String upLoadFile(HttpServletRequest request, String destPath){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("uploadFile");
String fileName = file.getOriginalFilename();
String extName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
Random random =new Random();
fileName = System.currentTimeMillis()+String.valueOf(random.nextInt(10000))+extName;//重命名文件名称
String dirPath = destPath.substring(0,destPath.lastIndexOf(File.separator));
FileTool.createDirectory(dirPath);
try {
//上传文件
if (file != null && !file.isEmpty()) {
// 文件复制
String fullPath = destPath + File.separator + fileName;
File localFile = new File(fullPath);
BufferedReader in = new BufferedReader (new FileReader (localFile.getPath()));
in.close ();
file.transferTo(localFile);
return fileName;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
spring mvc 上传:
/**
* 上传文件(单个文件)
* @param request req请求
* @param destPath 文件保存路径
* @return 上传后文件名
* 注意:uploadFile 为 前端 input file 的name属性
*/
public static String upLoadFile(HttpServletRequest request, String destPath){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("uploadFile");
String fileName = file.getOriginalFilename();
String extName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
Random random =new Random();
fileName = System.currentTimeMillis()+String.valueOf(random.nextInt(10000))+extName;//重命名文件名称
String dirPath = destPath.substring(0,destPath.lastIndexOf(File.separator));
FileTool.createDirectory(dirPath);
try {
//上传文件
if (file != null && !file.isEmpty()) {
// 文件复制
String fullPath = destPath + File.separator + fileName;
File localFile = new File(fullPath);
BufferedReader in = new BufferedReader (new FileReader (localFile.getPath()));
in.close ();
file.transferTo(localFile);
return fileName;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询