我正在阅读xlsx文件并希望在我的服务器上编写它。我正在获取文件名并将文件内容写入临时目录。
当我执行项目时。它在我的服务器上创建了文件,并在其中写入1kb
内容。但是当我打开它时,它说file format or file extention
无效。
@RequestMapping(value = "/uploadFile")
public String uploadFileHandler(@ModelAttribute UploadFile uploadFile,
@RequestParam("filename") String name
/* @RequestParam("file") MultipartFile file*/) {
if (!name.isEmpty()) {
try {
byte[] bytes = name.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();
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.";
}
}
JSP:
JS:
function uploadTemplate()
{
var filename = document.getElementById("filename").value;
document.uploadRequest.action = "uploadFile?filename="+filename;
document.uploadRequest.submit();
}
HTML:
<form:form action="" method="POST" modelAttribute="uploadFile" name="uploadRequest" enctype="multipart/form-data">
<div align="center" style="margin-bottom: 10px;">
<button onClick = "downloadTemplate()" style="width:250px" type="submit" class="admin_search_btn"><spring:message code="lblDownloadXls"></spring:message></button>
</div>
<div align="center" style="margin-bottom: 10px;" >
<form:input path="fileName" style="width:200px" id="filename" class="admin_search_btn" type="file" />
<div align="center" style="margin-bottom: 10px;" >
<button onClick = "uploadTemplate()" type="submit" class="admin_search_btn"><spring:message code="lblSubmit"></spring:message></button>
<button type="submit" class="admin_search_btn">Cancel</button>
</div>
</div>
</form:form>
答案 0 :(得分:0)
Ok现在,我在某种程度上理解了你的问题,这是我的答案
您正尝试使用名称filename将上传的文件(uploadFile)写入服务器。
改变你的喜好。
if (!name.isEmpty()) {
try {
**// Here read the content of uploadFile (not of the name)**
byte[] bytes = name.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));
**// Write the content of the uploadfile not the filename**
stream.write(bytes);
stream.close();
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.";
}
答案 1 :(得分:-1)
尝试使用Apache POI库写入xlsx。