带有附件的上传,下载,一个多个附件的上传,下载及测试类


	/**
	 * 新增证照
	 * 
	 * @param content
	 * @return
	 */
	@POST
	@Path("/")
	@Consumes("multipart/form-data")
	Response add(@Multipart("content") String content,Attachment attachments);




/**
	 * 保存单个照片
	 * 
	 * @param attachment
	 *            附件
	 * @param serNum
	 *            证照编码
	 * @return
	 */
	private String saveSiglePhoto(Attachment attachment, String serNum) {
		String photoName = null;
		String fileName = null;
		String filePath = null;
		if (null != attachment) {

			DataHandler dh = attachment.getDataHandler();
			try {
				photoName = new String(dh.getName().getBytes("ISO-8859-1"),
						"UTF-8");
				fileName = serNum
						+ photoName.substring(photoName.indexOf("."),
								photoName.length());
				filePath = "gzydt/licenseTemplate/";
				writeFile(dh, fileName, filePath);

			} catch (Exception e) {
				e.printStackTrace();

			}
		}

		return filePath + fileName;

	}

	/**
	 * 创建文件
	 * 
	 * @param dh
	 * @param fileName
	 * @throws IOException
	 */
	private void writeFile(DataHandler dh, String fileName, String filePath)
			throws IOException {
		InputStream is = dh.getInputStream();
		File file = new File(filePath);
		// File file = new File(filePath + fileName);
		if (!file.exists()) {
			file.mkdirs();
		}
		writeToFile(is, filePath + fileName);
	}

	/**
	 * 把内容写入文件中
	 * 
	 * @param is
	 * @param path
	 * @throws IOException
	 */
	private void writeToFile(InputStream is, String path) throws IOException {

		File file = new File(path);
		OutputStream out = new FileOutputStream(file);
		int len = 0;
		byte[] bytes = new byte[1024];
		while ((len = is.read(bytes)) != -1) {
			out.write(bytes, 0, len);
		}
		out.flush();
		out.close();

	}


多个附件上传:

/**
	 * 批量导入证照
	 * 
	 * @param attachment
	 *          excel文件,和zip文件
	 * @return
	 */
	@POST
	@Path("/batchAdd")
	@Consumes("multipart/form-data")
	Response batchAdd(List<Attachment> attachment);

下载附件:

 /**
     * 文件下载
     * 
     * @deprecated
     * @param name
     *            文件名
     * @return 流文件
     */
    @GET
    @Path("/{name}")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response download(@PathParam("name") String name);

@Override
    public Response download(String name) {
        // TODO 根据文件id获取服务器上的文件
        final File file = new File(PATH, name);
        if ( !file.exists() ) {
            return Response.status(Status.NOT_FOUND).entity("找不到文件:" + file.getName()).build();
        }

        StreamingOutput entity = new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                int len = 0;
                byte[] buffer = new byte[1024];
                InputStream inputStream = new FileInputStream(file);
                while ( (len = inputStream.read(buffer)) > 0 ) {
                    output.write(buffer, 0, len);
                }
                inputStream.close();
                output.flush();
                output.close();
            }
        };

        String type = MediaType.APPLICATION_OCTET_STREAM;

        String filename = file.getName().toLowerCase();
        // TODO 在浏览器打开特殊格式文件,可以使用Enum
        if ( filename.endsWith(".jpg") || filename.endsWith(".png") ) {
            type = "image/jpeg";
        } else if ( filename.endsWith(".doc") ) {
            type = "application/msword;charset=utf-8";
        } else if ( filename.endsWith(".pdf") ) {
            type = "application/pdf;charset=utf-8";
        }
        try {
            filename = new String(file.getName().getBytes("UTF-8"), "ISO-8859-1");
        } catch ( UnsupportedEncodingException e ) {
        }
        return Response.ok(entity, type).header("Content-Disposition", "inline;filename=" + filename).build();

    }

测试附件上传类:

/**
 * 批量导入文件
 */
	@Test
	public void batchAdd() {
		// 要上传的文件
		
		  // 要上传的文件
        String path1 = "F:/44070420090318151173.zip";
        String path2 = "F:/中华人民共和国残疾人证.xls";
        try {
            long start = System.currentTimeMillis();

            File file1 = new File(path1);
            File file2 = new File(path2);
           
            // 文件及其他信息
            Part[] parts = { new CustomFilePart(file1.getName(), file1),
            		new CustomFilePart(file2.getName(), file2), };
          
			PostMethod post = new PostMethod(LIC_IMAGE_URL+"/batchAdd");
			post.setRequestEntity(new MultipartRequestEntity(parts, post
					.getParams()));
			HttpClient httpclient = new HttpClient();
			String res = "";

			try {
				int result = httpclient.executeMethod(post);
				log.info("Response status code: " + result);
				log.info("Response body: ");
				res = getStringFromInputStream(post.getResponseBodyAsStream());
				log.info(res);
			} catch (Exception e) {
				log.error("Error connecting to {}", LIC_IMAGE_URL);
				Assert.fail("Connection error");
			} finally {
				// Release current connection to the connection pool once you
				// are
				// done
				post.releaseConnection();
			}
			log.info("断言:验证成功返回消息包含id字符串!");
			Assert.assertTrue(res.contains("id"));
			long end = System.currentTimeMillis();
			log.info("验证用时(毫秒):" + (end - start));
		} catch (Exception e) {
			log.error("测试文件不存在,请修改测试代码或准备相应测试文件:" +path1);
			e.printStackTrace();
		}
	}

下载图片:

@Override
	public Response previewImage(String licId) {
		FormatLicense entity = formatLicenseService.get(licId);

		final BufferedImage image = watermark(entity);
		if (null == image) {
			return Response.status(404).entity("Not Found").build();
		}
		// 将图片以一个流的形式传给web客户端
		StreamingOutput stream = new StreamingOutput() {

			@Override
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				ImageIO.write(image, "png", output);
				output.flush();
				output.close();

			}
		};
		return Response.ok(stream, "image/jpeg")
				.header("Content-Disposition", "inline;filename=cert1.jpg")
				.build();
	}


/**
	 * 套打并盖章,完成证照图像的最后一步制作。印制到PDF文件上时只在本图像作比例缩小作业。
	 * 
	 * @param licType
	 *            证照类型
	 * @param page
	 *            证照源电文信息
	 * @return 供印制到PDF的证照图像
	 */

	private BufferedImage watermark(FormatLicense entity) {
		// 获取套打的照片的底图
		// TODO:底图的获取方法还为写
		// String page = this.getEntityString(entity);
		BufferedImage imgOfSrcImgPath = this.loadBufferedImage(entity
				.getTemplate());
		BufferedImage imageofTarget = new LienceTaoDa().markByText(
				imgOfSrcImgPath, entity, null, null);
		return imageofTarget;
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值