apache cxf restful的文件上传

@POST
	@Produces("application/json")
	@Path("/upload/{isSafe}")
	public String uploadFile(@PathParam("isSafe") String safe,MultipartBody body) {
		try {
			long t = new Date().getTime();
			for (Attachment a : body.getAllAttachments()) {
				//save file to location
				DataHandler handler = a.getDataHandler();
				ContentDisposition cd = a.getContentDisposition();
				String fileName = cd.getParameter("file");
				String npath = "";
				String dpath = "";
				int safeFlag = 1;

				if (safe.equals("safe")) {
					npath = path + "\\safe\\";
					dpath = dbFilePath + "safe/" + fileName;
				} else if (safe.equals("unsafe")) {
					npath = path + "\\unsafe\\";
					dpath = dbFilePath + "unsafe/" + fileName;
					safeFlag = 0;
				}

				if (npath.equals(""))
					return Constants.STATUS_FAIL_WITH_NOMSG;

				File f = new File(npath + fileName);
				System.out.println("file path:"+f.getAbsolutePath());
				if(handler.getInputStream().available()>0) System.out.println("get input stream");
				FileHelper.writeFileWithStream(f, handler.getInputStream());

				//update db
				String sql = "insert into file_info values(0,'" + dpath + "',"
						+ t + "," + safeFlag + ")";
				int i = JDBCHelper.getTemplate().update(sql);
				if (i < 1)
					return Constants.STATUS_FAIL_WITH_NOMSG;

				return Constants.STATUS_SUCCESS_WITH_NOMSG;
			}
			return Constants.STATUS_FAIL_WITH_NOMSG;
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.STATUS_FAIL_WITH_NOMSG;
		}
		
		
		
		
	}


public static void writeFileWithStream(File f,InputStream is){
		System.out.println("begin upload file:"+f.getAbsolutePath());
		try {
			if (!f.exists())
				f.createNewFile();
			else{
				f.delete();
				f.createNewFile();
			}
			OutputStream os = new FileOutputStream(f);
			byte buffer[] = new byte[4 * 1024];
			while (is.read(buffer) != -1)
				os.write(buffer);
			System.out.println("end upload file:"+f.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值