文件上传
2020-02-02 15:13
225 查看
文件上传:
文件上传,对流操作
将文件通过表单上传到服务器,服务器从request中将文件读取到输入流
在将输入流中的数据 通过输出流写入目的文件夹下即可
javaweb项目的lib文件夹 应该创建在web---- WEB-INF
fileupload:文件上传
commons-io:通用的io相关的工具jar包
文件上传的步骤
1、创建fileupload.html
2、创建fileuploadServlet
3、导入jar包
4、编码
fileuplaod.html:
注意:
1、文件上传请求方式只能用post
2、enctype="multipart/form-data"
fileuploadservlet:
见代码
上传了的文件 如何访问?
1、配置tomcat虚拟路径
<Context docBase="E:\file" path="/upload"/>
2、通过idea设置tomcat 勾选Deploy……
例如:
封装类:
public class FileUtils {
/**
* 获取真实的文件名
* @param name
* @return
*/
public static String getRealFileName(String name){
int index = name.lastIndexOf("\\");
return name.substring(index+1);
}
/**
* 生成文件名
* @param name
* @return
*/
public static String getUUIDFileName(String name){
UUID uuid = UUID.randomUUID();
String s = uuid.toString().replaceAll("-", "");
return s+name;
}
}
上传类:
@WebServlet(value = "/fileUploadServlet",name = "FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1、设置编码格式
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2、创建文件上传核心对象DiskFileItemFactory
DiskFileItemFactory factory = new DiskFileItemFactory();
//3、文件上传对象
ServletFileUpload upload = new ServletFileUpload(factory);
//设置相关参数
upload.setHeaderEncoding("utf-8");//防止中文名乱码
upload.setFileSizeMax(1024*1024*5);//单位:b
//4、解析request,将请求中的数据封装成FileItem
try {
List<FileItem> list = upload.parseRequest(request);
//遍历集合解析数据
for (FileItem item : list) {
if(item.isFormField()){//普通字段
}else{//表示是文件
//文件上传
//获取文件名
String filename = item.getName();
filename = FileUtils.getRealFileName(filename);
filename = FileUtils.getUUIDFileName(filename);
//确定存储路径
String filepath = "E:\\file";
File file = new File(filepath);
if(!file.exists()){
file.mkdirs();
}
//拼接上传路径
filepath = filepath+File.separator+filename;
System.out.println(filepath);
//获取输入流
InputStream in = item.getInputStream();
//获取输出流
FileOutputStream out = new FileOutputStream(filepath);
//复制
IOUtils.copy(in, out);
out.close();
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response );
}
}
转载于:https://www.cnblogs.com/wzhsc/p/10326630.html
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 原生JavaScript实现异步多文件上传
- java支持断点续传文件上传和下载组件
- structs文件上传与下载,解决文件乱码的例子
- nodejs 上传文件
- mvc文件上传支持批量上传,拖拽以及预览,文件内容校验
- windows下命令行终端使用rz上传文件参数详解
- 用filezilla往不同网段的局域网内的机器上传文件很慢 只有几十k
- PHP swfupload图片文件上传实例代码
- PHP socket文件上传 --转
- (ASP.NET)利用Fileupload上传文件到服务器(尝试1)
- PHP文件下载上传类
- 关于 javaweb的文件上传实时显示进度
- vue+elementui el-upload上传文件携带参数
- PHP上传文件
- hadoop的hdfs文件操作实现上传文件到hdfs
- SSH 利用SecureCRT上传、下载文件(使用sz与rz命令)
- SCP 从服务器上传下载文件
- Java web 中实现简单的文件上传与下载——学习笔记
- ASP.NET上传图片,服务器端验证,宽度,高度,文件类型,尺寸,文件大小,图片上传,图片格式检查
- 怎么在一个表单里面同时上传文件和文本信息??