您好,欢迎访问一九零五行业门户网

java如何上传文件

一:准备好前台页面upload.html
表单 action=上传文件后台接口 method=“post”enctype=“multipart/form-data”,文件输入框9146e572b55ac8e3a795b1d3ea0383cf
<form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="files"> <input type="submit" value="上传"></form>
二:加入相应的jar包
三:准备接收文件servlet
url路径一定要与上面表单的action保持一致
四:编写文件上传后台代码
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { try { // 配置上传参数 diskfileitemfactory factory = new diskfileitemfactory(); servletfileupload upload = new servletfileupload(factory); // 解析请求的内容提取文件数据 @suppresswarnings("unchecked") list<fileitem> formitems = upload.parserequest(request); // 迭代表单数据 for (fileitem item : formitems) { // 处理不在表单中的字段 if (!item.isformfield()) { string filename = item.getname(); //定义上传文件的存放路径 string path = request.getservletcontext().getrealpath("/uploadfiles"); //定义上传文件的完整路径 string filepath = string.format("%s/%s",path,filename); file storefile = new file(filepath); // 在控制台输出文件的上传路径 system.out.println(filepath); // 保存文件到硬盘 item.write(storefile); } } } catch (exception ex) { } }
五:准备存放上传文件的目录,注意和上面代码中的路径保持一致
完成!
推荐教程:java入门教程
以上就是java如何上传文件的详细内容。
其它类似信息

推荐信息