我正在尝试上传文件(使用Jquery和Servlet)
Servlet文件:
的 UploadServlet.java
public class UploadServlet extends HttpServlet {
private File fileUploadPath;
public void init(ServletConfig config) {
fileUploadPath = new File(config.getInitParameter("upload_path"));
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
File file = new File(fileUploadPath,request.getParameter("getfile"));
if (file.exists()) {
int bytes = 0;
ServletOutputStream op = response.getOutputStream();
response.setContentType("text/html");
response.setContentType(getMimeType(file));
response.setContentLength((int) file.length());
response.setHeader( "Content-Disposition", "inline; filename=\"" + file.getName() + "\"" );
byte[] bbuf = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
op.write(bbuf, 0, bytes);
}
in.close();
op.flush();
op.close();
}
} else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
File file = new File(fileUploadPath, request.getParameter("delfile"));
if (file.exists()) {
file.delete(); // TODO:check and report success
}
} else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
File file = new File(fileUploadPath, request.getParameter("getthumb"));
BufferedImage im =null;
if (file.exists()) {
String mimetype = getMimeType(file);
if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("gif")
{ im = ImageIO.read(file);
if (im != null) {
BufferedImage thumb = Scalr.resize(im, 75);
ByteArrayOutputStream os = new ByteArrayOutputStream();
if (mimetype.endsWith("png")) {
ImageIO.write(thumb, "PNG" , os);
response.setContentType("image/png");
} else if (mimetype.endsWith("jpeg")) {
ImageIO.write(thumb, "jpg" , os);
response.setContentType("image/jpeg");
} else if (mimetype.endsWith("gif")) {
ImageIO.write(thumb, "GIF" , os);
response.setContentType("image/gif");
}else{
ImageIO.write(thumb, "doc" , os);
response.setContentType("image/doc");
}
ServletOutputStream srvos = response.getOutputStream();
response.setContentLength(os.size());
response.setHeader( "Content-Disposition", "inline; filename=\"" + file.getName() + "\"" );
os.writeTo(srvos);
srvos.flush();
srvos.close();
}
}
}
} else {
PrintWriter writer = response.getWriter();
writer.write("call POST with multipart form data");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
}
DiskFileItemFactory ldch_disk_file = new DiskFileItemFactory();
ldch_disk_file.setRepository(fileUploadPath);
ServletFileUpload uploadHandler = new ServletFileUpload(ldch_disk_file);
PrintWriter writer = response.getWriter();
response.setContentType("application/json");
JSONArray json = new JSONArray();
try {
List<FileItem> items = uploadHandler.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
File file = new File(fileUploadPath, item.getName());
item.write(file);
JSONObject jsono = new JSONObject();
jsono.put("name", item.getName());
jsono.put("size", item.getSize());
jsono.put("url", "upload?getfile=" + item.getName());
jsono.put("thumbnail_url", "upload?getthumb=" + item.getName());
jsono.put("delete_url", "upload?delfile=" + item.getName());
jsono.put("delete_type", "GET");
json.put(jsono);
}
}
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
writer.write(json.toString());
writer.close();
}
}
private String getMimeType(File file) {
String mimetype = "";
if (file.exists()) {
if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
mimetype = "image/png";
} else if (getSuffix(file.getName()).equalsIgnoreCase("docx")) {
mimetype = "image/doc";
}else {
javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
mimetype = mtMap.getContentType(file);
} }
System.out.println("mimetype: " + mimetype);
return mimetype;
}
private String getSuffix(String filename) {
String suffix = "";
int pos = filename.lastIndexOf('.');
if (pos > 0 && pos < filename.length() - 1) {
suffix = filename.substring(pos + 1);
}
System.out.println("suffix: " + suffix);
return suffix;
}
源代码: Source Code Link