我使用以下代码成功上传了一个文本文件(例如 Another.java),但在尝试打开上传的文件时出现错误。提前致谢。
文件上传.jsp
<form action="test.jsp" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<br/>
<input type="submit" value="Upload">
</form>
</body>
测试.jsp
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%-- <%@page import="org.apache.commons.io.*" %> --%>
<%@page import="org.apache.commons.io.*"%>
<%@page import="org.apache.commons.fileupload.FileUploadException"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
try {
String username = "";
List<FileItem> items = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
if (fieldname.equals("vsrd")) {
username = fieldvalue;
}
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
byte[] b = new byte[filecontent.available()];
FileOutputStream fos = new FileOutputStream(
"/home/visruth/Desktop/Out" + filename);
fos.write(b);
fos.close();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
%>
尝试打开OutAnother.java
时出错:
最佳答案
在您的代码中,您刚刚创建了一个空字节数组。您尚未从 InputStream 读取内容。 Inputstream#available() 只是获取可用长度。它不会从 InputStream 读取内容。
典型的方法是从InputStream读取并写入OutputStream:
FileInputStream is = new FileInputStream(
new File("D:\\temp\\in.java"));
FileOutputStream os = new FileOutputStream(
new File("D:\\temp\\out.java"));
byte[] buff = new byte[1000];
int length = -1;
while ((length = is.read(buff)) != -1) {
os.write(buff, 0, length);
}
is.close();
os.close();
您还可以使用IOUtils#copy来自 commons-io 来完成这项工作。
关于java - Apache Commons 文件上传 - 上传后文件损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15333051/