文件的上传
@WebServlet("/up")
@MultipartConfig //使用MultipartConfig注解标注改servlet能够接受文件上传的请求
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Part part = req.getPart("myfile");
String disposition = part.getHeader("Content-Disposition");
String suffix = disposition.substring(disposition.lastIndexOf("."),disposition.length()-1);
//随机的生存一个32的字符串
String filename = UUID.randomUUID()+suffix;
//获取上传的文件名
InputStream is = part.getInputStream();
//动态获取服务器的路径
String serverpath = req.getServletContext().getRealPath("upload");
FileOutputStream fos = new FileOutputStream(serverpath+"/"+filename);
byte[] bty = new byte[1024];
int length =0;
while((length=is.read(bty))!=-1){
fos.write(bty,0,length);
}
fos.close();
is.close();
}
}
文件的下载
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String file = request.getParameter("file"); //客户端传递的需要下载的文件名
String path = request.getServletContext().getRealPath("")+"/"+file; //默认认为文件在当前项目的根目录
FileInputStream fis = new FileInputStream(path);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment; filename="+file);
ServletOutputStream out = response.getOutputStream();
byte[] bt = new byte[1024];
int length = 0;
while((length=fis.read(bt))!=-1){
out.write(bt,0,length);
}
out.close();
}
}