1.前端form代码
<form action="/xxx" method="post" enctype="multipart/form-data" >
请选择文件:<input id="file" name="file" type="file" />
<input type="submit" value="上传" />
</form>
2.后端获取
后端可以通过request获取信息
若想打印上传信息需要对二进制流进行解码
request.setCharacterEncoding("utf-8");//重新设置request编码方式
BufferedReader reader=new BufferedReader(new InputStreamReader(fileSourceStream,"UTF-8"));
StringBuffer sb=new StringBuffer();
String line=null;
try {
while ((line=reader.readLine())!=null){
sb.append(line+"\n");
}
}catch (IOException e){
e.printStackTrace();
}finally {
reader.close();
}
System.out.println(sb.toString());
//以下为打印信息
------WebKitFormBoundaryOrJaw5CZ99brCJ5M
Content-Disposition: form-data; name="file"; filename="解压方式.txt"
Content-Type: text/plain
www.baidu.com
这是一个测试文件
解压内容如下:
------WebKitFormBoundaryOrJaw5CZ99brCJ5M--
3.如何对获取的信息进行处理
显然不能用request.getParameter进行处理了
已经能获取到文件的名称以及内容了,所以可以自己编写字符串/bit处理的代码对有效信息进行提取(再解码),但是已经有提供好的jar包帮助我们对流进行处理,无需自己进行处理了
3.1利用Apache的Commons-fileupload
官方文档:http://commons.apache.org/proper/commons-fileupload/using.html
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
//1.获取FileItem的集合
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//2.遍历FileItem 的集合,若是表单域... 若是文件域...
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
//表单域
} else {
//文件域
InputStream inputStream=item.getInputStream();
OutputStream outputStream=new FileOutputStream(new File("H:\\files\\"+item.getName()));//写入files目录下
System.out.println(item.getFieldName());
System.out.println(item.getName());
int len=0;
byte[] buffer=new byte[1024];
while ((len=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
outputStream.close();
inputStream.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}