javax.servlet.http.Part#getContentType()源码实例Demo

下面列出了javax.servlet.http.Part#getContentType() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void prepareSendPartHeader_update(@Mocked Part part) {
  new Expectations() {
    {
      part.getContentType();
      result = "type";
      part.getSubmittedFileName();
      result = "测     试";
    }
  };
  DownloadUtils.prepareDownloadHeader(response, part);

  Assert.assertTrue(serverResponse.isChunked());
  Assert.assertEquals("type", response.getHeader(HttpHeaders.CONTENT_TYPE));
  Assert.assertEquals(
      "attachment;filename=%E6%B5%8B%20%20%20%20%20%E8%AF%95;filename*=utf-8''%E6%B5%8B%20%20%20%20%20%E8%AF%95",
      response.getHeader(HttpHeaders.CONTENT_DISPOSITION));
}
 
@Test
public void fileBoundaryInfo_nullSubmittedFileName(@Mocked Part part) {
  new Expectations() {
    {
      part.getSubmittedFileName();
      result = null;
      part.getContentType();
      result = "abc";
    }
  };
  RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null);
  Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part);
  Assert.assertEquals("\r\n" +
      "--boundary\r\n" +
      "Content-Disposition: form-data; name=\"name\"; filename=\"null\"\r\n" +
      "Content-Type: abc\r\n" +
      "Content-Transfer-Encoding: binary\r\n" +
      "\r\n", buffer.toString());
}
 
@Test
public void fileBoundaryInfo_validSubmittedFileName(@Mocked Part part) {
  new Expectations() {
    {
      part.getSubmittedFileName();
      result = "a.txt";
      part.getContentType();
      result = MediaType.TEXT_PLAIN;
    }
  };
  RestClientRequestImpl restClientRequest = new RestClientRequestImpl(request, null, null);
  Buffer buffer = restClientRequest.fileBoundaryInfo("boundary", "name", part);
  Assert.assertEquals("\r\n" +
      "--boundary\r\n" +
      "Content-Disposition: form-data; name=\"name\"; filename=\"a.txt\"\r\n" +
      "Content-Type: text/plain\r\n" +
      "Content-Transfer-Encoding: binary\r\n" +
      "\r\n", buffer.toString());
}
 
源代码4 项目: HongsCORE   文件: UploadHelper.java
/**
 * 检查上传对象并写入目标目录
 * @param part
 * @param subn
 * @return
 * @throws Wrong
 */
public File upload(Part part, String subn) throws Wrong {
    if (part == null) {
        setResultName("", null);
        return  null;
    }

    /**
     * 从上传项中获取类型并提取扩展名
     */
    String type = part.getContentType( /**/ );
           type = getTypeByMime( type );
    String extn = part.getSubmittedFileName();
           extn = getExtnByName( extn );

    try {
        return upload(part.getInputStream(), type, extn, subn);
    }
    catch ( IOException ex) {
        throw new Wrong(ex, "fore.form.upload.failed");
    }
}
 
源代码5 项目: requests   文件: MockMultiPartServlet.java
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);

    Collection<Part> parts = request.getParts();

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    OutputStream out = response.getOutputStream();
    for (Part part : parts) {
        out.write(part.getName().getBytes(StandardCharsets.UTF_8));
        out.write('\n');
        if (part.getContentType() != null) {
            out.write(part.getContentType().getBytes(StandardCharsets.UTF_8));
            out.write('\n');
        }
        try (InputStream in = part.getInputStream()) {
            InputStreams.transferTo(in, out);
        }
        out.write('\n');
    }
}
 
源代码6 项目: molgenis   文件: MenuManagerController.java
/** Upload a new molgenis logo */
@PreAuthorize("hasAnyRole('ROLE_SU')")
@PostMapping("/upload-logo")
public String uploadLogo(@RequestParam("logo") Part part, Model model) throws IOException {
  String contentType = part.getContentType();
  if ((contentType == null) || !contentType.startsWith("image")) {
    model.addAttribute("errorMessage", ERRORMESSAGE_LOGO);
  } else {
    // Create the logo subdir in the filestore if it doesn't exist
    File logoDir = new File(fileStore.getStorageDir() + "/logo");
    if (!logoDir.exists() && !logoDir.mkdir()) {
      throw new IOException("Unable to create directory [" + logoDir.getAbsolutePath() + "]");
    }

    // Store the logo in the logo dir of the filestore
    String file = "/logo/" + FileUploadUtils.getOriginalFileName(part);
    try (InputStream inputStream = part.getInputStream()) {
      fileStore.store(inputStream, file);
    }

    // Set logo
    appSettings.setLogoNavBarHref(file);
  }

  return init(model);
}
 
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Throwable ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
源代码10 项目: tephra   文件: HttpUploadReader.java
HttpUploadReader(Part part, Map<String, String> map) throws IOException {
    this.part = part;
    name = part.getName();
    fileName = part.getSubmittedFileName();
    contentType = part.getContentType();
    size = part.getSize();
    inputStream = part.getInputStream();
    this.map = map;
}
 
@Override
public String getMultipartContentType(String paramOrFileName) {
	try {
		Part part = getPart(paramOrFileName);
		return (part != null ? part.getContentType() : null);
	}
	catch (Exception ex) {
		throw new MultipartException("Could not access multipart servlet request", ex);
	}
}
 
源代码12 项目: lucene-solr   文件: SolrRequestParsers.java
public PartContentStream(Part part ) {
  this.part = part;
  contentType = part.getContentType();
  name = part.getName();
  sourceInfo = part.getSubmittedFileName();
  size = part.getSize();
}
 
源代码13 项目: OnlineShoppingSystem   文件: SellerServiceImpl.java
public boolean addGoodsImage(HttpServletRequest request, int goodsId) {
    boolean flag = false;
    int count = -1;
    ArrayList<Part> images;
    try {
        images = (ArrayList<Part>) request.getParts();
        count = images.size();
        for (Part image : images) {
            if (image.getContentType() == null) {
                continue;
            }
            // System.out.println(image.getContentType());
            InputStream imageInputStream = null;

            if (image != null && image.getSize() != 0) {
                try {
                    imageInputStream = image.getInputStream();

                    if (imageInputStream != null) {
                        String imagedir = request.getServletContext()
                                .getInitParameter("imagedir")
                                + File.separator;
                        // 图片名格式:20161123204206613375.jpg。
                        // 代表 2016-11-23 20:42:06.613 + 3 位 0 - 9 间随机数字
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
                        StringBuilder imageName = new StringBuilder(
                                dateFormat.format(new Date()));
                        Random random = new Random();
                        for (int i = 0; i < 3; ++i) {
                            imageName.append(random.nextInt(10));
                        }
                        imageName.append(".jpg");

                        String targetFile = imagedir + imageName;
                        try {
                            FileUtils.copyInputStreamToFile(imageInputStream,
                                    new File(targetFile));
                            count--;

                            dao.addGoodsImage("/images/goods/" + imageName, goodsId);   // 更新数据库

                            // System.out.println(imagedir);
                            // System.out.println(imageName);
                            // System.out.println(count);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                } finally {
                    imageInputStream.close();
                }
            }
        }
    } catch (IOException | ServletException e3) {
        e3.printStackTrace();
    }
    if (count == 0) {
        flag = true;
    } else {
        flag = false;
    }

    return flag;
}
 
源代码14 项目: Tutorials   文件: FileUploadServlet.java
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	response.setContentType("text/html");
	response.setCharacterEncoding("UTF-8");

	// gets absolute path of the web application
	String applicationPath = request.getServletContext().getRealPath("");
	// constructs path of the directory to save uploaded file
	String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

	// creates upload folder if it does not exists
	File uploadFolder = new File(uploadFilePath);
	if (!uploadFolder.exists()) {
		uploadFolder.mkdirs();
	}

	PrintWriter writer = response.getWriter();

	// write all files in upload folder
	for (Part part : request.getParts()) {
		if (part != null && part.getSize() > 0) {
			String fileName = part.getSubmittedFileName();
			String contentType = part.getContentType();
			
			// allows only JPEG files to be uploaded
			if (!contentType.equalsIgnoreCase("image/jpeg")) {
				continue;
			}
			
			part.write(uploadFilePath + File.separator + fileName);
			
			writer.append("File successfully uploaded to " 
					+ uploadFolder.getAbsolutePath() 
					+ File.separator
					+ fileName
					+ "<br>\r\n");
		}
	}

}
 
源代码15 项目: BLELocalization   文件: ImportServlet.java
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	InputStream is = null;
	OutputStream os = null;
	try {
		Part part = null;
		try {
			part = request.getPart("file");
		} catch (Exception e) {
		}
		String contentType = null;
		int contentLength = -1;
		if (part == null) {
			is = request.getInputStream();
			contentType = request.getContentType();
			contentLength = request.getContentLength();
		} else {
			is = part.getInputStream();
			contentType = part.getContentType();
			contentLength = (int) part.getSize();
		}
		response.addHeader("Access-Control-Allow-Origin", "*");
		if (contentType != null) {
			response.setContentType(contentType);
		}
		if (contentLength > 0) {
			response.setContentLength(contentLength);
		}
		os = response.getOutputStream();
		byte data[] = new byte[4096];
		int len = 0;
		while ((len = is.read(data, 0, data.length)) > 0) {
			os.write(data, 0, len);
		}
		os.flush();
	} finally {
		if (is != null) {
			is.close();
		}
		if (os != null) {
			os.close();
		}
	}
}
 
源代码16 项目: BotLibre   文件: MemoryUploadServlet.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PageStats.page(request);
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	
	LoginBean loginBean = (LoginBean)request.getSession().getAttribute("loginBean");
	if (loginBean == null) {
		response.sendRedirect("index.jsp");
		return;
	}
	BotBean botBean = loginBean.getBotBean();
	MemoryBean bean = loginBean.getBean(MemoryBean.class);
	try {
		String postToken = (String)request.getParameter("postToken");
		loginBean.verifyPostToken(postToken);
		String instance = (String)request.getParameter("instance");
		if (instance != null) {
			if (botBean.getInstance() == null || !String.valueOf(botBean.getInstanceId()).equals(instance)) {
				botBean.validateInstance(instance);
			}
		}
		if (!botBean.isConnected()) {
			request.getRequestDispatcher("memory.jsp").forward(request, response);
			return;
		}
		botBean.checkAdmin();
		String importFormat = (String)request.getParameter("import-format");
		String encoding = (String)request.getParameter("import-encoding");
		String pin = (String)request.getParameter("pin");
		Part filePart = request.getPart("file");
		if ((filePart != null) && (filePart.getSize() > 0)) {
			if (filePart.getContentType() != null && filePart.getContentType().equals("csv")) {
				importFormat = "csv";
			}
			String fileName = getFileName(filePart);
			InputStream stream = filePart.getInputStream();
			bean.importFile(fileName, stream, importFormat, encoding, "on".equals(pin));
		} else {
			throw new BotException("Missing file");
		}
		request.getRequestDispatcher("memory.jsp").forward(request, response);
	} catch (Exception failed) {
		botBean.error(failed);
		request.getRequestDispatcher("memory.jsp").forward(request, response);
	}
}
 
源代码17 项目: portals-pluto   文件: MultipartPortlet.java
@ActionMethod(portletName = "MultipartPortlet")
public void handleDialog(ActionRequest req, ActionResponse resp) throws IOException, PortletException {
   List<String> lines = new ArrayList<String>();
   req.getPortletSession().setAttribute("lines", lines);

   lines.add("handling dialog");
   StringBuilder txt = new StringBuilder(128);

   String clr = req.getActionParameters().getValue("color");
   txt.append("Color: ").append(clr);
   lines.add(txt.toString());
   logger.debug(txt.toString());

   resp.getRenderParameters().setValue("color", clr);

   txt.setLength(0);
   Part part = null;
   try {
      part = req.getPart("file");
   } catch (Throwable t) {}
   
   if ((part != null) && (part.getSubmittedFileName() != null) && 
         (part.getSubmittedFileName().length() > 0)) {
      txt.append("Uploaded file name: ").append(part.getSubmittedFileName());
      txt.append(", part name: ").append(part.getName());
      txt.append(", size: ").append(part.getSize());
      txt.append(", content type: ").append(part.getContentType());
      lines.add(txt.toString());
      logger.debug(txt.toString());
      txt.setLength(0);
      txt.append("Headers: ");
      String sep = "";
      for (String hdrname : part.getHeaderNames()) {
         txt.append(sep).append(hdrname).append("=").append(part.getHeaders(hdrname));
         sep = ", ";
      }
      lines.add(txt.toString());
      logger.debug(txt.toString());

      // Store the file in a temporary location in the webapp where it can be served. 

      try {
         String fn = part.getSubmittedFileName();
         String ct = part.getContentType();
         
         if (ct != null && (ct.equals("text/plain") || ct.matches("image/(?:png|gif|jpg|jpeg)"))) {
            
            String ext = ct.replaceAll("\\w+/", "");
            lines.add("determined extension " + ext + " from content type " + ct);
            File img = getFile();
            if (img.exists()) {
               lines.add("deleting existing temp file: " + img.getCanonicalPath());
               img.delete();
            }
            InputStream is = part.getInputStream();
            Files.copy(is, img.toPath(), StandardCopyOption.REPLACE_EXISTING);
            
         } else {
            lines.add("Bad file type. Must be plain text or image (gif, jpeg, png).");
         }

         resp.getRenderParameters().setValue("fn", fn);
         resp.getRenderParameters().setValue("ct", ct);

      } catch (Exception e) {
         lines.add("Exception doing I/O: " + e.toString());
         
         txt.setLength(0);
         txt.append("Problem getting temp file: " + e.getMessage() + "\n");
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         pw.flush();
         txt.append(sw.toString());
         logger.warn(txt.toString());
      }
   } else {
      lines.add("file part was null");
   }

}