我正在做一个服务项目,它的UI允许用户上传文件。我需要写一个服务,可以把这个文件上传到服务器,并读取和显示这个文件的内容。谁能告诉我怎么做?
//Controller definition begins
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public @ResponseBody
String uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
logger.info("Server File Location="
+ serverFile.getAbsolutePath());
return "You successfully uploaded file=" + name;
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
现在我想知道如何显示上传文件的内容。它被转换为FILE格式,存储在tomcat服务器的tempfiles目录中,数据是非人类可读的。我需要将其转换回xlsx(正在上传的文件是xlsx),或者能够直接从它读取数据以更新数据库。此外,我正在使用apache commons-io和文件上传在Spring MVC,你可以从上面的代码看到。
您需要一个能够读取xlsx文件类型的库,例如Apache POI
如果你选择了这个库,在它的网站的示例部分有一个非常好的示例部分