您的位置:首页 > 其它

文件上传

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

  • 点赞
  • 收藏
  • 分享
  • 文章举报
ahao4311 发布了0 篇原创文章 · 获赞 0 · 访问量 150 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: