javaweb:jsp,servlet往服务器上传文件
直接上个源代码
package res.servlets;
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.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@MultipartConfig//必须加上这一行的配置不然part用不了
@WebServlet("/uploadServlet.do")//这个是相应jsp的action,因为这里设置了所以webxml不用设置
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Part part = request.getPart("file");
String filename = getFileName(part);
System.out.println("收到file"+filename);
saveData(filename,part);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
获取文件名
*/
protected static String getFileName(Part part){
String header = part.getHeader("Content-Disposition");
String filename = header.substring(header.indexOf("filename=\"")+10,header.lastIndexOf("\""));
return filename;
}
/**
把数据储存到本地
*/
protected static void saveData(String filename, Part part) throws IOException {
InputStream in = part.getInputStream();
OutputStream out = new FileOutputStream("c:/down/"+filename);//路径可以自己选择
byte[] buffer = new byte[1024];
int length = -1;
while((length=in.read(buffer))!=-1){
out.write(buffer);
}
in.close();
out.close();
}
}
这个是jsp的代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="uploadServlet.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" value=""><br>
<input type="submit" name="upload" value="Upload"><br>
</form>
</body>
</html>
这个小demo要注意的点是part的使用,必须添加MultipartConfig标签,不然就会驾崩(500)。
然后jsp中的form表单的action要对应。