团队冲刺8 5.9
servlet接收并保存前台或app传来的文件。
以下是一个简单的例子。
package servlet; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; 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 org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @WebServlet("/Ejdkm") public class Ejdkm extends HttpServlet { private static final long serialVersionUID = 1L; public Ejdkm() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); DiskFileItemFactory factory = new DiskFileItemFactory(); //创建缓冲区 String temp = this.getServletContext().getRealPath("地址");//缓冲区地址 factory.setSizeThreshold(1024 * 1024 * 100); //缓冲区大小 factory.setRepository(new File(temp)); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); try{ List<FileItem> list = servletFileUpload.parseRequest(request); for (FileItem item : list) { String name = item.getFieldName(); InputStream is = item.getInputStream(); if (name.contains("num")){ } else if(name.contains("file")){ try { inputStream2File(is,"要保存的地址\\文件名字"); } catch (Exception e) { e.printStackTrace(); } } } } catch (FileUploadException e) { e.printStackTrace(); } response.getWriter().append("你的返回值"); out.flush(); out.close(); } public String inputStream2String(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = -1; while ((i = is.read()) != -1) { baos.write(i); } return baos.toString(); } public void inputStream2File(InputStream is,String savePath) throws Exception{ File file = new File(savePath); InputStream inputSteam = is; BufferedInputStream fis = new BufferedInputStream(inputSteam); FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[10240]; int len; while((len = fis.read(b)) != -1){ fos.write(b, 0, len); } fos.flush(); fos.close(); fis.close(); inputSteam.close(); } }