JavaServlet接收上传⽂件
在Java中使⽤ Servlet 来接收⽤户上传的⽂件,需要⽤到两个apache包,分别是包;
如果直接在doPost中,使⽤InputStream()获取ServletInputStream,这样获取到的Stream是不能直接写⼊⽂件的,⽐如上传⼀个txt⽂件,你会发现保存下来的txt⽂件不只有原本txt⽂件本⾝的内容,⾥⾯还有post请求的⼀些参数,⽐如参数分割符等;
下⾯就是⼀个使⽤fileupload包来接收⽂件内容的例⼦:
public class FileServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -4187075130535308117L;
private boolean isMultipart;
private int maxFileSize = 1024 * 1024 * 10;
private int maxMemSize = 100 * 1024;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 检查是否有⼀个⽂件上传请求
isMultipart = ServletFileUpload.isMultipartContent(request);
String result = "";
response.setContentType("text/html;charset=utf-8");
if (!isMultipart) {
result = "未获取到⽂件";
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// ⽂件⼤⼩的最⼤值将被存储在内存中
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
String path = getServletContext().getRealPath("/") + "/";
factory.setRepository(new File(path));
// System.out.println(path);
// 创建⼀个新的⽂件上传处理程序
ServletFileUpload upload = new ServletFileUpload(factory);
// 允许上传的⽂件⼤⼩的最⼤值
upload.setSizeMax(maxFileSize);
inputtypefile不上传文件try {
// 解析请求,获取⽂件项
List fileItems = upload.parseRequest(request);
// 处理上传的⽂件项
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
/
/ 获取上传⽂件的参数
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// 写⼊⽂件
File file = new File(path + System.currentTimeMillis() / 1000 + ".py");
fi.write(file);
}
}
result = "上传成功";
} catch (Exception ex) {
System.out.println("ex:" + ex.getMessage());
result = "上传失败";
}
}
}
接下来,在html页⾯中,可以通过在⼀个表单中来提交上传⽂件
<form action="fileUpload" enctype="multipart/form-data" method="post">
<input type="file" name="file"></input><input type="submit"
value="提交"></input>
</form>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论