用户将带有txt扩展名的文件上传到我的系统。我希望此文件可以www.exp.com/text_file.txt
但我不能这样做。
Project/src/main/webapp/text_file.txt
,如果我将文件放在webapp下,我可以得到它。
但是如何在webapp中创建txt文件?
new File(---);
- >这段代码不是我想要的。它在eclipse文件夹下创建。
Project
->pom.xml
->src
->main
->java
->resources
->webapp
->WEB-INF
答案 0 :(得分:0)
假设您正在使用servlet,此代码应该可以运行(让文件放入webapp / resources)
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
// Getting ServletContext from request
ServletContext ctx= req.getServletContext();
// Get the absolute path of the file
String filename = ctx.getRealPath("resources/file.text");
// getting mimeType of the file
String mime = ctx.getMimeType(filename);
// Error handling
if (mime == null) {
res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Setting MIME content type
res.setContentType(mime);
// Getting file object
File file = new File(filename);
// Setting content length header
res.setContentLength((int)file.length());
// FileInputStream to read from file
FileInputStream in = new FileInputStream(file);
// Obtain OutputStream from response object
OutputStream out = res.getOutputStream();
// Writing to the OutputStream
byte[] buffer = new byte[1024];
int bytes = 0;
// we stop when in.read returns -1 and read untill it does not
while ((bytes = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
// Clean up, closing resources
out.close();
in.close();
}