标签:
这个先进些,简单些,但书上提供的例子不能使用,到处弄了弄才行。
servlet代码:
package cc.openhome; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.FileNotFoundException; import java.io.File; import java.io.IOException; 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; /** * Servlet implementation class UploadServlet */ @WebServlet("/upload.do") @MultipartConfig public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //request.setCharacterEncoding("UTF-8"); Part part = request.getPart("photo"); //String uploadPath = request.getServletContext().getRealPath("/upload"); String fileName = getFileName(part); System.out.println(fileName + "*****************"); writeTo(fileName, part); } private String getFileName(Part part) { 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 FileNotFoundException, IOException { String uploadPath = "c:/workspace"; part.write(uploadPath + File.separator + fileName); /*** InputStream in = part.getInputStream(); OutputStream out = new FileOutputStream("c:/workspace" + fileName); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); ***/ } }
标签:
原文地址:http://www.cnblogs.com/aguncn/p/5468508.html