我正在开发一个服务项目,其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)或者能够从中读取数据它直接更新Db.Also我在Spring MVC中使用apache commons-io和文件上传,你可以从上面的代码中看到。
答案 0 :(得分:0)
您需要一个能够读取xlsx文件类型的库,例如Apache POI
如果您选择此库,则会有very good example section in the example secion of it's website