Skip to content

Instantly share code, notes, and snippets.

@9SQ 9SQ/Uploader.java
Created Oct 15, 2014

Embed
What would you like to do?
multipart/form-dataで受けたデータを保存&Paramsも取得 (Tomcat7/Servlet3.0)
import java.io.IOException;
import java.io.PrintWriter;
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 org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
@WebServlet("/Upload")
@MultipartConfig(location = "/tmp", maxFileSize = 1000000, maxRequestSize = 1000000, fileSizeThreshold = 1000000)
public class Uploader extends HttpServlet {
private static final long serialVersionUID = 1L;
public Uploader() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF8");
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.print("test");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF8");
PrintWriter out = response.getWriter();
if (ServletFileUpload.isMultipartContent(request)) {
// fileの取得
Part filePart = request.getPart("file");
/* ここにファイルの判定が必要かも(スクリプトなどの設置防止) */
String fileName = "";
String partHeader = filePart.getHeader("content-disposition");
for (String cd : partHeader.split(";")) {
if (cd.trim().startsWith("filename")) {
fileName = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
out.println(fileName);
}
}
filePart.write(fileName);
// params取得
String paramText = request.getParameter("text");
out.println(paramText);
} else {
out.print("error");
System.out.println("error");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.