<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/java0209/demo04" method="get"> 用户名<input type="text" name="username"> <input type="submit" value="提交"> </form> </body> </html>
package com.atping.servlet_; import org.apache.commons.io.IOUtils; 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; @WebServlet("/demo05") @MultipartConfig public class HttpServlet05 extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("username"); String password = req.getParameter("password"); Part picture = req.getPart("picture"); String pictureName = picture.getName(); System.out.println("用户名" + username + "密码" + password + "文件名字" + pictureName); //文件具体名字 String fileName = picture.getSubmittedFileName(); InputStream inputStream = picture.getInputStream(); //用绝对路径和相对路径分别演示 /正斜杠单个 //双斜杠两个 // String imgPath = req.getServletContext().getRealPath("img"); FileOutputStream outputStream = new FileOutputStream("D:\\代码\\February\\java0209\\web\\img\\"+fileName); byte[] bytes = new byte[1024]; int len = 0; while ((len = inputStream.read(bytes)) != -1){ outputStream.write(bytes,0,len); } // IOUtils.copy(inputStream,outputStream); outputStream.close(); } }
标签:文件,String,picture,上传,req,import,servlet,javax From: https://www.cnblogs.com/p1121/p/17104838.html