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();
		}
	}


你可能感兴趣的:(quick,reference)