【发布时间】:2014-09-28 23:31:35
【问题描述】:
我正在读取 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>
【问题讨论】:
-
看起来您正在尝试编写“名称”参数而不是内容。这是你想要做的吗?你能举个文件名参数值的例子吗?
-
@Maas:我添加了jsp内容
-
但是你正在写字节:byte[] bytes = name.getBytes();那不是更新文件的内容。
你应该做的是为文件名创建另一个文件并读取它的内容。 -
@Maas:如果我创建了另一个文件名,那么我也需要在其中写入。我应该在那里写什么内容?
-
@user123 你在用
Struts