Java Web实现文件上传
upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="/upload.do" method="post" enctype="multipart/form-data">
文件上传<input type="file" name="file" >
<input type="submit" value="提交">
</form>
</body>
</html>
将文件上传到BodyServlet.java会得到文件字节
上传的UploadServlet.java会得到文件
BodyServlet.java
//获取文件字节内容
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.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/Body.view")
public class BodyServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("ISO-8859-1");
String body = readBody(req);
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>");
out.println("asd");
out.println("</title>");
out.println("<body>");
out.println(body);
out.println("</body>");
out.println("</html>");
}
private String readBody(HttpServletRequest request) throws IOException {
BufferedReader reader = request.getReader();
String input = null;
String requestBody = "";
while ((input = reader.readLine()) != null) {
requestBody = requestBody + input + "<br>";
}
return requestBody;
}
}
uploadServlet.java
//第一种上传方式,原生获取
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.DataInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
byte[] body = readBody(req);
String textBody = new String(body, "ISO-8859-1");
String filename = GetFilename(textBody);
Position p = GetFilePosition(req, textBody);
writeto(filename, body, p);
}
//文件内容定位类定义
class Position {
int begin;
int end;
Position(int begin, int end) {
this.begin = begin;
this.end = end;
}
}
//读取文件内容
private byte[] readBody(HttpServletRequest request) throws IOException {
int FormDataLength = request.getContentLength();
DataInputStream dataInputStream = new DataInputStream(request.getInputStream());
byte[] body = new byte[FormDataLength];
int totalBody = 0;
while (totalBody < FormDataLength) {
int bytes = dataInputStream.read(body, totalBody, FormDataLength);
totalBody += bytes;
}
return body;
}
//获取文件内容定位
private Position GetFilePosition(HttpServletRequest request, String textBody) throws IOException {
String contentType = request.getContentType();
String boundaryText = contentType.substring(contentType.lastIndexOf("=") + 1, contentType.length());
int pos = textBody.indexOf("filename=\"");
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
pos = textBody.indexOf("\n", pos) + 1;
int boundaryLoc = textBody.indexOf(boundaryText, pos) - 4;
int begin = ((textBody.substring(0, pos)).getBytes("ISO-8859-1")).length;
int end = (textBody.substring(0, boundaryLoc).getBytes("ISO-8859-1")).length;
return new Position(begin, end);
}
//获取文件名
private String GetFilename(String reqBody) throws IOException {
String filename = reqBody.substring(reqBody.indexOf("filename=\"") + 10);
filename = filename.substring(0, filename.indexOf("\n"));
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.indexOf("\""));
filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
return filename;
}
//写入文件
private void writeto(String filename, byte[] body, Position position) throws FileNotFoundException, IOException {
FileOutputStream fileOutputStream = new FileOutputStream("E:/temp/" + filename);
fileOutputStream.write(body, position.begin, (position.end - position.begin));
fileOutputStream.flush();
fileOutputStream.close();
}
}
//第二种上传方式,通过getPart上传,需加@MultipartConfig
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@MultipartConfig
@WebServlet("/upload1.do")
public class UploadServlet1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part = req.getPart("name");
String filename = GetFilename(part);
writeto(filename, part);
}
//获取文件名
private String GetFilename(Part part) throws IOException {
String header = part.getHeader("Content-Disposition");
String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
return filename;
}
//写入文件
private void writeto(String filename, Part part) throws IOException, FileNotFoundException {
InputStream inputStream = part.getInputStream();
FileOutputStream out = new FileOutputStream("E:/temp/" + filename);
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
inputStream.close();
out.close();
}
}
//第三钟上传方式,通过getPart中的write方法写入
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
@MultipartConfig(location = "E:/temp")
@WebServlet("/upload2.do")
public class UploadServlet2 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Part part = req.getPart("name");
String filename = GetFilename(part);
part.write(filename);
}
private String GetFilename(Part part) {
String header = part.getHeader("Content-Disposition");
String filename = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
return filename;
}
}