DiskFileItemFactory实现文件上传FileInputStream下载
FileInputStream 是 Java 输入流的一种,用于从文件中读取数据。它是字节流,适用于读取二进制文件。
1.文件上传
```java
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class FileUploadServlet extends HttpServlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart)
FileItemFactory factory = new DiskFileItemFactory(;
ServletFileUpload upload = new ServletFileUpload(factory);
try
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items)
if (!item.isFormField() {  // 如果是文件字段
String fileName = Name(;
String filePath = "/path/to/save/uploads/" + fileName;  // 保存文件的路径
File file = new File(filePath);
item.write(file);  // 将文件保存到指定路径
Writer(.write("File uploaded successfully.");
}
}
} catch (Exception e)
Writer(.write("File upload failed.");
}
}
}
```
上述代码中,首先判断请求是否为多部分内容(即文件上传)。然后创建一个 DiskFileItemFactory 对象和一个 ServletFileUpload 对象。通过调用 `upload.parseRequest(request)` 解析请求,得到一个包含上传的文件字段的 FileItem 列表。遍历 FileItem 列表,如果是文件字段,则获取文件名和保存路径,创建一个 File 对象,最后将文件保存到指定路径。
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
public class FileDownloadServlet extends HttpServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
String fileName = "";
File file = new File(filePath);
if (ists()
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
FileInputStream fis = new FileInputStream(file);
OutputStream os = OutputStream(;
byte[] buffer = new byte[4096];
int bytesRead;
java创建文件while ((bytesRead = ad(buffer)) != -1)
os.write(buffer, 0, bytesRead);
}
fis.close(;
os.close(;
} else
Writer(.write("File not found.");
}
}
```

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。