/UploadServlet.java Secret
Last active
March 13, 2016 21:31
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
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("/myUpload") | |
@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#doGet(HttpServletRequest request, HttpServletResponse | |
* response) | |
*/ | |
protected void doGet(HttpServletRequest request, | |
HttpServletResponse response) throws ServletException, IOException { | |
// TODO Auto-generated method stub | |
} | |
/** | |
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse | |
* response) | |
*/ | |
protected void doPost(HttpServletRequest request, | |
HttpServletResponse response) throws ServletException, IOException { | |
Part filePart = request.getPart("file"); | |
// obtain file name from header | |
String content = filePart.getHeader("content-disposition"); | |
String filename = ""; | |
for (String token : content.split(";")) { | |
if (token.trim().startsWith("filename")) { | |
System.out.println(token); | |
filename = token.substring(token.indexOf("=") + 2, | |
token.length() - 1); | |
System.out.println(filename); | |
} | |
} | |
// path where the file will be placed: | |
String path = "C:\\uploads"; | |
System.out.println(path); | |
// obtain file content | |
InputStream fileContent = filePart.getInputStream(); | |
OutputStream out = new FileOutputStream(new File(path + File.separator | |
+ filename)); | |
int read = 0; | |
final byte[] bytes = new byte[1024]; | |
while ((read = fileContent.read(bytes)) != -1) { | |
out.write(bytes, 0, read); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment