servlet实现文件上传接收
这几天学了一点文件上传,有很多不会,在网查了许多博客,但是最新的没有,都比较久了
因为我是小白,版本更新了,以前的方法自己费了好久才弄懂,写个随笔方便以后查找
代码奉上:
package com.test;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
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.ServletInputStream;
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.util.Date;
import java.util.List;
import java.util.Random;
public class UpFileServlet extends HttpServlet {
// 返回指定长度的随机字符串;
public static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<length;i++){
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
// 需要导入两个jar包,commons-fileupload-1.2.1.jar和commons-io-1.4.jar
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*ServletInputStream servletInputStream = req.getInputStream();
byte[] buffer = new byte[102400];
int read = servletInputStream.read(buffer);*/
// 1、判断是否多段数据
if(ServletFileUpload.isMultipartContent(req)){
// FileItemFactory 创建工厂实现类;
FileItemFactory fileItemFactory = new DiskFileItemFactory();
// 创建用于解析上传数据的工具类ServletFileUpload类;
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
// 解析上传的数据,得到每一个表单项;
try {
List<FileItem> list =servletFileUpload.parseRequest(req);
for (FileItem fileItem:list) {
// yes是不同表单项,no是上传的文件
if (fileItem.isFormField()){
System.out.println("表单项的name值:"+ fileItem.getName());
System.out.println("表单项的value值:"+fileItem.getString("UTF-8"));
}else {
System.out.println("表单项的name属性值:"+fileItem.getFieldName());
String fileName = fileItem.getName();
System.out.println("表单项的文件名:"+fileName);
String midName = getRandomString(4);
System.out.println(midName);
String lastName = fileName.substring(fileName.indexOf('.'));
String newFileName = new Date().getTime()+midName+lastName;
fileItem.write(new File("D://"+newFileName));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片文件上传与解析</title>
</head>
<body>
<form action="/test/upFile" method="post" enctype="multipart/form-data">
<span>username</span><br>
<input type="text" placeholder="请输入对图片的描述" name="username"><br>
<span>选择文件</span>
<input type="file" name="myfile" id="file"><br>
<input type="submit" value="确认">
</form>
</body>
</html>
需要注意的是;
该方法需要依赖两个jar包,代码注释中已说明