@RequestMapping("/onefile")
public Object oneFileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request,
ModelMap model) throws IOException {
boolean bo;
// 获得原始文件名
String fileName = file.getOriginalFilename();
// 新文件名
DateFormat dateTimeformat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String newFileName = dateTimeformat.format(new Date())+fileName.replaceAll(" ", "");
// 获得项目的路径
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String path = sc.getRealPath("\\resources\\upload") + "\\";
File f = new File(path);
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
//start
FileInputStream in = (FileInputStream) file.getInputStream();
FileOutputStream out = new FileOutputStream(new File(path + newFileName));
try {
FileChannel fcIn = in.getChannel();
FileChannel fcOut = out.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int r = fcIn.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcOut.write(buffer);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
in.close();
out.close();
}
//end
}
bo = true;
// 保存文件地址,用于JSP页面回显
model.addAttribute("fileUrl", path + newFileName);
return bo;
}
主要是
FileChannel fcIn = in.getChannel();
FileChannel fcOut = out.getChannel();
//提升
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int r = fcIn.read(buffer);
if (r == -1) {
break;
}
buffer.flip();
fcOut.write(buffer);
}