.JavaWeb文件上传和FileUpload组件使用

.JavaWeb文件上传

1.自定义上传

文件上传时的表单设计要符合文件提交的方式:

1.提交方式:post

2.表单中有文件上传的表单项:<input type="file"/>

3.指定表单类型:文件上传类型: enctype=“multipart/form-data”`

jsp上传页面:

<%--
Created by IntelliJ IDEA.
User: cenyu
Date: 16-12-20
Time: 下午8:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username">
文件:<input type="file" name="file1"><br/>
<input type="submit" value="提交上传">
</form>
</body>
</html>

Servlet处理程序:

package test;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; /**
* 手动处理文件上传
* Created by cenyu on 16-12-20.
*/
@WebServlet("/upload")
public class uploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
request.getQueryString();//获取GET:username=Tom&pwd=888
request.getInputStream();//获取POST:inputStream
request.getParameter("");//使用这个可以不区分get和post
*/
//获取表单(POST)数据
ServletInputStream in = request.getInputStream();//此方法得到所有的提交信息,不仅仅只有内容
//转换流
InputStreamReader inReaser = new InputStreamReader(in);
//缓冲流
BufferedReader reader = new BufferedReader(inReaser);
String str = null;
while ((str=reader.readLine()) != null){
System.out.println(str);
} }
}

提交测试文件:

aaaaaaaaa
bbbbbbbbb
ccccccccc
dddddddd

运行结果:

-----------------------------468783950766433362585077246
Content-Disposition: form-data; name="username" cenyu
-----------------------------468783950766433362585077246
Content-Disposition: form-data; name="file1"; filename="test.txt"
Content-Type: text/plain aaaaaaaaa
bbbbbbbbb
ccccccccc
dddddddd
-----------------------------468783950766433362585077246--

2.FileUpload组件

FileUpload组件,也叫文件上传组件,是Apache提供的开源项目

组件使用方法:

1.下载,引入jar文件

引入commons-fileupload-1.2.1.jar

引入依赖包commons-io-1.4.jar

3.Api学习

文件上传组件API

FileItemFactory 文件上传工厂类(把每一个请求表单项封装为一个个FileItem对象)

fac.setRepository(repository);设置上传临时目录

ServletFileUpload 文件上传核心类,可以获取所有的FileItem对象

list pload.parseRequest(request);

Boolean isMultipartContent(request);判断表单类型,文件上传表单但会true

upload.setFileSizeMax(fileSizeMax);设置单个上传文件的最大值

upload.setSizeMax(sizeMax);设置总上传文件大总的最大值

upload.setHeaderEcoding("UTF-8");设置上传文件名的编码

FileItem 封装了普通表单项的值以及文件上传表单元素的值

item.getFiledName();获取上传表单元素的名称

item.getString();获取上传数据;

item.getString("UTF-8");获取上传数据,处理中文

item.getContentType();获取上传文件类型[文件上传项]

item.getInputStream();获取文件流[文件上传项]

item.getName();获取文件名[文件上传项]

item.write(file);把数据写到file文件

item.delete();删除临时文件

使用FileUpload组件来写上传方法的整体代码:

需求:

1.设置单个文件不能超过30M

2.设置总大小不能超过50M

3.上传目录,上传到项目资源目录下的upload目录

4.上传文件不能覆盖,解决上传文件名的同名问题

前端jsp页面中的代码没有改变,只需要看FileUploadServlet中的代码:

package Upload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.attribute.FileTime;
import java.util.List;
import java.util.UUID; /**
* 文件上传组件完整使用
* Created by cenyu on 16-12-20.
*/
@WebServlet("/load")
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
} protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建文件上传工厂类
DiskFileItemFactory fac = new DiskFileItemFactory();
//2.创建文件上传核心类对象
ServletFileUpload upload = new ServletFileUpload(fac);
//【一、设置单个文件最大30M】
upload.setFileSizeMax(30*1024*1024);//30M
//【二、设置总文件大小:50M】
upload.setSizeMax(50*1024*1024); //50M //判断,当前表单是否为文件上传表单
if (upload.isMultipartContent(request)){ try {
//3.把请求数据转换为FileItem对象的集合
List<FileItem> list = upload.parseRequest(request);
//遍历,得到每一个上传项
for (FileItem item : list){
//判断:是普通表单项,还是文件上传表单项
if (item.isFormField()){
//普通表单x
String fieldName = item.getFieldName();//获取元素名称
String value = item.getString("UTF-8"); //获取元素值
System.out.println(fieldName+" : "+value); }else {
//文件上传表单 String name = item.getName(); //上传的文件名称
/**
* 【四、文件重名】
* 对于不同的用户的test.txt文件,不希望覆盖,
* 后台处理:给用户添加一个唯一标记!
*/
//a.随机生成一个唯一标记
String id = UUID.randomUUID().toString();
//与文件名拼接
name = id + name; //【三、上传到指定目录:获取上传目录路径】
String realPath = getServletContext().getRealPath("/upload");
//创建文件对象
File file = new File(realPath, name);
item.write(file);
item.delete();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else {
System.out.println("不处理!");
} }
}
上一篇:TestNG运作报错An interanl error occurred during:"Launching first"


下一篇:How to fix the sources list